题目描述
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.
代码
public String countAndSay(int n) {
String init = "1";
for (int i = 1; i < n; i++) {
init = countAndSay(init);
}
return init;
}
String countAndSay(String string) {
char[] str = string.toCharArray();
String s = "";
int p = 1;
int count = 1;
char last = str[0];
for (; p < str.length; p++) {
if (str[p] == last) {
count++;
} else {
s += "" + count + last;
count = 1;
last = str[p];
}
}
s += "" + count + last;
return s;
}