Saturday, April 5, 2014

leetcode: Count and Say

public class Solution {
   public String countAndSay(int n) {
        String s1 = "1";
        for(int i = 1; i < n; i++){
            String s2 = "";
            char[] sChars = s1.toCharArray();
            int j = 1, count = 1;
            while(j < sChars.length){
                while(j < sChars.length && sChars[j] == sChars[j-1])
                {
                    j++;
                    count++;
                }
                s2 = s2 + count + sChars[j-1];
                j++;
                count = 1;
            }
            if(sChars.length < 2 || sChars[sChars.length-1] != sChars[sChars.length -2])
             s2 = s2 + count + sChars[j-1];
            s1 = s2;
        }
        return s1;
    }
}

No comments:

Post a Comment