题目:
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.
思路:
Easy级别的题目,没有算法上的技巧:一共做n次循环,每次统计出字符串中连续相同的字符,并将结果添加临时字符串中;每次循环结束之后将临时字符串赋值给返回结果。不过对于这种对字符串进行递增修改的情况,如果用stringstream则效率要比string的+=高不少,在Leetcode上的测试结果也印证了这一点。
所以建议这一题目在C++实现中,就采用stringstream类型来记录临时字符串;在Java中建议采用StringBuilder实现,效率一定要比string高不少。
代码:
class Solution {
public:
string countAndSay(int n) {
string str = "1";
for(int i = 1; i < n; ++i)
{
stringstream tem;
int cnt = 1;
char ch = str[0];
for(int idx = 1; idx < str.size(); ++idx)
{
if(str[idx] == ch)
{
++cnt;
}
else
{
tem << cnt << ch;
cnt = 1;
ch = str[idx];
}
}
tem << cnt << ch;
str = tem.str();
}
return str;
}
};