2014年11月30日星期日

[Leetcode] 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.

Simple string manipulation problem, mainly about finding repeating characters sequences. I used two pointers to find the continuous characters.

    public String countAndSay(int n) {
        String str = "1";
        while(n > 1) {
            int p1 = 0, p2 = 0;
            StringBuffer sb = new StringBuffer();
            while(p1 < str.length()) {
                while(p2 < str.length() && str.charAt(p1) == str.charAt(p2))
                    p2++;
                sb.append(String.valueOf(p2 - p1));
                sb.append(str.charAt(p1));
                p1 = p2;
            }
            str = sb.toString();
            n--;
        }
        return str;
    }

没有评论:

发表评论