Count and Say

The count-and-say sequence is defined as a sequence start with 1 and the following ones count and say the previous one. The sequence is like:

1, 11, 21, 1211, 111221. From 1 to 11 we say "one 1" which is 11. Then we say "two 1" which is 21. Then we say "one 2 one 1" which is 1211.

Given a number n, return the nth number in a count-and-say sequence.

Solution:

1. We write a "sayout" function with a string parameter and return its count-and-say result. Then we can get the result by calling this method n-1 times.

2. In the sayout function, we use a char variable to store current char and a count variable to count the number of current char. The char variable can be initialized as the first char and count can be initialized as 1.

3. Scan the whole String, whenever we encounter the char that is not the same as its previous one, we add the count and current char to the result. Otherwise just add up count by 1. After scanning the whole String we put the current char and count into the result string and return it.

Code:

public class Solution {
    public String countAndSay(int n) {
        String temp = "1";
        while(--n>0){
            temp = sayOut(temp);
        }
        return temp;
    }
    private String sayOut(String s){
        int count = 1;
        char curr = s.charAt(0);
        StringBuilder result = new StringBuilder();
        for(int i = 1; i < s.length(); i++){
            if(s.charAt(i)==s.charAt(i-1))
                count++;
            else{
                result.append(count);
                result.append(curr);
                curr = s.charAt(i);
                count=1;
            }
        }
        result.append(count);
        result.append(curr);
        return result.toString();
    }
}
View Code

 

posted @ 2017-06-20 08:59  小风约定  阅读(64)  评论(0)    收藏  举报