38. Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

public class Solution {
    public String countAndSay(int n) {
        if(n == 0) return "";
        String s = "1";
        for(int j = 1; j < n; j++){
            StringBuilder sb = new StringBuilder();
            // 通过记录上次的字符来判断是否重复
            char last = s.charAt(0);
            int cnt = 1;
            for(int i = 1; i < s.length(); i++){
                if(s.charAt(i) == last){
                    // 如果重复则计数器加1
                    cnt++;
                } else {
                    // 否则添加上一个字符,并重置计数器为1
                    sb.append(cnt);
                    sb.append(last);
                    last = s.charAt(i);
                    cnt = 1;
                }
            }
            // 最后记得把最后一个字符加上
            sb.append(cnt);
            sb.append(last);
            s = sb.toString();
        }
        return s;
    }
}

//另外也可以稍作变化用递归方法

/*
public class Solution {
    public String countAndSay(int n) {
        if(n == 0) return "";
        // 计算出上一个字符串
        String s = "1";
        StringBuilder sb = new StringBuilder();
        // 通过记录上次的字符来判断是否重复
        char last = s.charAt(0);
        int cnt = 1;
        for(int i = 1; i < s.length(); i++){
            // 如果重复则计数器加1
            if(s.charAt(i) == last){
                cnt++;
            } else {
            // 否则添加上一个字符,并重置计数器为1
                sb.append(cnt);
                sb.append(last);
                last = s.charAt(i);
                cnt = 1;
            }
        }
        // 最后记得把最后一个字符加上
        sb.append(cnt);
        sb.append(last);
        return sb.toString();
    }
}*/

留下评论