Count and Say 420

Question

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.

Notice

The sequence of integers will be represented as a string.

Example

Given n = 5, return "111221".

Solution

遍历上一个字符串,记下当前字符连续重复出现的次数,将次数+当前元素加入本次答案。

代码如下:

public class Solution {
    /**
     * @param n the nth
     * @return the nth sequence
     */
    public String countAndSay(int n) {
        // Write your code here
        if(n < 1){
            return "";
        }

        String s = "1";
        for(int i = 1; i < n; i++){
            String next = "";
            int j = 0;
            while(j < s.length()){
                int start = j;
                char curt = s.charAt(j++);
                while(j < s.length() && s.charAt(j) == curt){
                    j++;
                }
                int num = j - start;
                next += num + Character.toString(curt);
            }
            s = next;
        }

        return s;
    }
}

results matching ""

    No results matching ""