题目描述:
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.
程序代码:
class Solution {
public:
string countAndSay(int n) {
string s = "1";
// 循环n次得到最终的s
for (int i = 1; i < n; i++) {
string newS = "";
// 对于每次循环,顺序遍历字符串,得出连续相同数字的重复次数,并由此得到新的字符串
for (int i = 0; i < s.size(); i++) {
char temp = s[i];
int count = 1;
while (s[++i] == temp) {
count++;
}
i--;
newS += (char)(48 + count);
newS += temp;
}
s = newS;
}
return s;
}
};
本题关键是要理解题意,需要理解“”count-and-say sequence“的意思。最开始思考时,我认为本题需要使用递归才容易实现,但实际做时我发现使用循环即可比较简单地完成。开始时先初始化一个字符串s=“1”,然后按照题意,进行n次循环后得到最终的字符串。在这n次循环中的每次循环,都需要按照题意进行操作:首先对原字符串进行顺序遍历,找到连续的相同的数字,并得出其重复次数,然后将重复次数和该数字添加到新的字符串末尾。这样遍历完整个字符串后就得到一个新的字符串,并完成了本次循环。n次循环操作后得到的就是最终的字符串了。
通过本题我意识到审题的重要性,有时题目算法并不算太难,理解题意,理清思路,才能让解题事半功倍。