The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
题意:这道题的题意真的是非常的复杂我真的是读了很久还是没读懂。。。
这道题的含义是,数数字,1对应的就是字符串“1”,从2开始数前面的,所以它前面是“11”,3读的是2,2里面有两个1,所以是“21”,4,读的是3,因为3是“21”,所以4是1个2,1个1,是“1211”。
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
java代码:
public String countAndSay(int n) {
if (n == 1) {
return "1";
} else {
String output = countAndSay(n - 1), result = "";
int index = 0;
while (index < output.length()) {
char current = output.charAt(index);
int cursor = index, count = 0;
while (cursor < output.length() && output.charAt(cursor) == current) {
cursor++;
count++;
}
char number = (char)(count + '0');
result += number;
result += current;
index += count;
}
return result;
}
}