题目原址
https://leetcode.com/problems/count-and-say/description/
题目描述
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example1:
Input: 1
Output: “1”
Example2:
Input: 4
Output: “1211”
解题思路
该题的题目描述简直太烂了!!!
题目的大意应该是这样的:
(1)当n等于1时,输出“1”;
(2)当n等于2时,要看n-1中输出的信息,将输出的信息用口语读出来,口语读的结果作为n=2的输出值,(因为n=1时输出1,所以,口语读的结果是:1个1,所以n=2的输出结果是:11)
(3)当n等于3时,要看n-1中输出的信息,将输出的信息用口语读出来,口语读的结果作为n=3的输出值,(因为n=2时输出11,所以,口语读的结果是:2个1,所以n=3的输出结果是:21)
(4)当n等于4时,因为n=3时输出21,所以口语读的结果是:1个2,1个1,所以n=4的输出结果是1211
(5)当n等于5时,因为n=4时输出1211,所以口语读的结果是:1个1,1个2,2个1,所以n=5的输出结果是111221
(6)。。。以此类推
所以就将上述步骤转变为代码就可以解决该题了
因为当前的结果依赖于前面的输出结果,所以要记录前面的输出结果,就是递归!
AC代码
class Solution {
public String countAndSay(int n) {
String s = "1";
for(int i = 1; i < n; i++) {
s = count(s);
}
return s;
}
String count(String s) {
StringBuffer sb = new StringBuffer();
char c = s.charAt(0);
int count = 1;
for(int i = 1; i < s.length(); i++) {
if(s.charAt(i) == c)
count++;
else {
sb.append(count);
sb.append(c);
c = s.charAt(i);
count = 1;
}
}
sb.append(count);
sb.append(c);
return sb.toString();
}
}
感谢
https://leetcode.com/problems/count-and-say/discuss/16040/Straightforward-Java-Solution