leetcode学习笔记21

38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211

class Solution {
    public String countAndSay(int n) {
        StringBuilder s=new StringBuilder();
        if(n==1)
            return "1";
        char[] chs=countAndSay(n-1).toCharArray();       
        for(int i=0;i<chs.length;i++){
                int count=1;
                while(i<chs.length-1&&chs[i+1]==chs[i]){
                    count++;
                    i++;
                }
                s.append(count);
                s.append(chs[i]);
        }
        return s.toString();                                 
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38941866/article/details/85000768
今日推荐