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

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integern, generate thenthterm of the count-and-say sequence.

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

思路: 读了写,读了写

public class Solution {
    public String countAndSay(int n) {
        String s = "1";
        for (int i=1;i<n;i++){
            s = count(s);
        }
        return s;
    }


    public String count(String s){
        StringBuilder sb = new StringBuilder();
        char c = s.charAt(0);
        int count = 1;
        for (int i=1;i<s.length();i++){
            if (s.charAt(i)==c){
                count++;
            }else{
                sb.append(count);
                sb.append(c);
                c = s.charAt(i);
                count = 1;
            }
        }
        sb.append(count);
        sb.append(c);
        return sb.toString();
    }
}

results matching ""

    No results matching ""