String - 38. Count and Say

时间:2022-07-25
本文章向大家介绍String - 38. Count and Say,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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.

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:

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();
    }
}