Count and Say

 1 public class Solution {
 2    public String countAndSay(int n) {
 3     String res = "1";
 4     if(n==0)  return res;
 5     for(int i=1;i<n;i++){
 6         res =get(res);
 7     }
 8     return res;
 9     }
10     
11     public String get(String res){
12         int count = 1;
13         char last=' ';
14         String temp ="";
15         for(int i=0;i<res.length();i++){
16             if(i<res.length()-1 && res.charAt(i)==res.charAt(i+1)){
17                 count++;
18                 last = res.charAt(i+1);
19             }
20             else{
21                 if(count>1){
22                     temp = temp+count+last;
23                     count = 1;
24                 }
25                 else{
26                     temp = temp+count+res.charAt(i);
27                 }
28             }
29         }
30         return temp;
31     }
32 }
View Code

n=1: 1

n=2:1 1

n=3: 2 1

n=4: 1211

n=5:111221

n=6:312211

posted @ 2014-02-12 04:01  krunning  阅读(120)  评论(0编辑  收藏  举报