String - 38. Count and Say

2020-09-23 17:12:55 浏览数 (1)

38. Count and Say

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

代码语言:javascript复制
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.

Given an integer n where 1 ≤ n ≤ 30, generate the _n_th term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string. Example 1:

Input: 1 Output: "1"

思路:

没有什么算法,就是暴力求解,从1开始,对每一位相同和不同的字符进行记录。

代码:

java:

代码语言:javascript复制
class Solution {

    public String countAndSay(int n) {

        StringBuilder curr = new StringBuilder("1");
        StringBuilder prev;
        
        int count = 0, i = 1;
        char say;
        
        while (i < n) {
            prev = curr;
            curr = new StringBuilder();
            count = 1;
            say = prev.charAt(0);
            
            // say str
            for (int j = 1; j < prev.length(); j  ){
                if (prev.charAt(j) != say) {
                    curr.append(count).append(say);
                    count = 1;
                    say = prev.charAt(j);
                } else {
                    // same char
                    count  ;
                }
            }
            
            i  ;
            curr.append(count).append(say);
        }
        
        return curr.toString();
    }
}

0 人点赞