Friday, March 1, 2013

[LeetCode] Count and Say

Thought:
Scan From the start, if we find some different character, we append a local result and continue to scan.
 
public class Solution {
    public String countAndSay(int n) {
        String result = "1";
        int time = 1;
        while(time < n){
            result = count(result);
            time++;
        }
        return result;
    }

    public String count(String s) {
        char[] tmp = s.toCharArray();
        StringBuilder result = new StringBuilder();
        for(int i = 0; i < tmp.length; i++) {
            int count = 1;
            while(i < tmp.length - 1 && tmp[i] == tmp[i + 1]) {
                i++;
                count++;
            }
            result.append(String.valueOf(count) + String.valueOf(tmp[i]));
        }
        return result.toString();
    }
}

No comments:

Post a Comment