# Leetcode_38_count-and-say

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.

public class TestCountAndSay {
private static String countAndSay;

public static void main(String[] args) {
countAndSay = countAndSay(12);
System.err.println(countAndSay);
}

public static  String countAndSay(int n) {
String value = String.valueOf(n);
for (int i = 0; i < n; i++) {
value = getAllSays(value);
}
return value;
}

public  static String getAllSays(String value){
StringBuffer buffer = new StringBuffer();
int len = value.length();
int pos = 0;
int max = 1;
for (int i = 1; i <=len;i++ ) {
if(i<len && (int)value.charAt(i) == (int)value.charAt(pos)){
max++;
continue;
}else{
buffer.append(String.valueOf(max));
buffer.append(value.charAt(pos));
pos = i;
max = 1;
}

}
return buffer.toString();
}
}

	public static String countAndSay(int n) {
if (n == 1) return "1";
String s = "1";
StringBuffer buffer = new StringBuffer();
//记录重复的值
int count = 0;
// 迭代次数
int round = 0;
int i;
while (++round < n) {
count = 1;
buffer.setLength(0);
for (i = 1; i < s.length(); i++) {
// 重复的值，继续计数
if (s.charAt(i) == s.charAt(i - 1)) {
count++;
} else {
// 有新的值出现，记录到buffer
buffer.append(count).append(s.charAt(i - 1));
// 重置count
count = 1;
}
}
buffer.append(count).append(s.charAt(i - 1));
// 更新s
s = buffer.toString();
}
return buffer.toString();
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120