Tuesday, April 12, 2016

[LeetCode] 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 countAndSayAux(String s){
        int len = s.length();
        StringBuilder sb = new StringBuilder();
        if(0 == len)
            return sb.toString();
        
        int c = 1;
        for(int i = 1; i < len; ++i){
            if(s.charAt(i) == s.charAt(i-1)){
                c++;
            }
            else{
                sb.append(Integer.toString(c).charAt(0));
                sb.append(s.charAt(i-1));
                c = 1;
            }
        }
        sb.append(Integer.toString(c).charAt(0));
        sb.append(s.charAt(len-1));
        return sb.toString();
    }
    
    public String countAndSay(int n) {
        String ret = new String("1");
        while(--n > 0){
            ret = countAndSayAux(ret);
        }
        return ret;
    }
}

No comments:

Post a Comment