"Appearance number of columns" is a sequence of integers, beginning with the number 1, is the description of the preceding each item in the sequence. The first five are as follows:
1.1
2.11
3.21
4.1211
5.111221
1 is read as "one 1" ( "a a"), i.e., 11.
11 is read as "two 1s" ( "two one"), i.e., 21.
21 is read as "one 2", "one 1 " ( " a two", "a a"), i.e., 1211.
Given a positive integer n (1 ≤ n ≤ 30), the n-th series term output appearance.
Note: Each sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Explanation: This is a basic sample.
Example 2:
Input: 4
Output: "1211"
Explanation: When n = 3, the sequence is "21", which we have "2" and "1" groups, "2" can be read as "12", i.e. occurrence frequency = = 1 and the value 2; similarly "1" can be read as "11." So the answer is "12" and "11" are combined, that is, "1211."
1 public class T38 { 2 public String countAndSay(int n) { 3 String str = "1"; 4 for (int i = 2; i <= n; i++) { 5 int count = 1; 6 StringBuilder sb = new StringBuilder(); 7 char pre = str.charAt(0); 8 for (int j = 1; j < str.length(); j++) { 9 char c = str.charAt(j); 10 if (pre == c) { 11 count++; 12 } else { 13 sb.append(count).append(pre); 14 pre = c; 15 count = 1; 16 } 17 } 18 sb.append(count).append(pre); 19 str = sb.toString(); 20 } 21 return str; 22 23 } 24 }