image.png

思路 循环

从4->5分析,将4个每一位拆开看(个数+数字),4=1211 => 1=11,2=12,11=21,所以5=111221
* 所以解题用循环,从1->n可求解出来

  1. public String countAndSay(int n) {
  2. String str = "1";
  3. for(int i=2;i<=n;i++){
  4. StringBuilder builder = new StringBuilder();
  5. char pre = str.charAt(0);
  6. int count = 1;
  7. for(int j=1;j<str.length();j++){
  8. char c = str.charAt(j);
  9. if(c==pre)
  10. count++;
  11. else{
  12. builder.append(count).append(pre);
  13. pre=c;
  14. count=1;
  15. }
  16. }
  17. builder.append(count).append(pre);
  18. str=builder.toString();
  19. }
  20. return str;
  21. }