38. Count and Say java solutions

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.

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         if(n < 1) return "";
 4         String res = "1";
 5         int s = 1;
 6         while(s < n){
 7             StringBuilder sb = new StringBuilder();
 8             int count = 1;
 9             for(int i = 1; i< res.length();i++){
10                 if(res.charAt(i) == res.charAt(i-1)) count++;
11                 else{
12                     sb.append(count).append(res.charAt(i-1));
13                     count = 1;
14                 }
15             }
16             sb.append(count).append(res.charAt(res.length()-1));
17             res = sb.toString();
18             s++;
19         }
20         return res;
21     }
22 }
原文地址:https://www.cnblogs.com/guoguolan/p/5640744.html