6/01/2014

78. Count and Say

public class Solution {
    public String countAndSay(int n) {
        if(n == 1) return "1";
         
        String res = "1";
        StringBuffer temp = new StringBuffer();
       
        int cnt = 0;
        int round = 0;
        int i;
       
        while(++round < n){
            cnt = 1;
            temp.setLength(0);
           
            for(i=1; i<res.length(); i++){
                if(res.charAt(i) == res.charAt(i-1)){
                    cnt++;
                }else{
                    temp.append(cnt).append(res.charAt(i-1));
                    cnt = 1;
                }
            }
            temp.append(cnt).append(res.charAt(i-1));
            res = temp.toString();
        }
       
        return res;
    }
}

没有评论:

发表评论