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.
題意:這道題的題意真的是非常的復雜我真的是讀了很久還是沒讀懂。。。
這道題的含義是,數(shù)數(shù)字,1對應的就是字符串“1”,從2開始數(shù)前面的,所以它前面是“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;
}
}