题目链接:Count and Say
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.
这道题的要求是数数并记录,生成序列中第n个字符串。
这道题算就是字符串处理的问题,序列中第一个字符串是“1”,接下来依次统计前一个字符串中连续相同字符的数量,并添加到下一字符串中。前15字符串如下(LeetCode上貌似只有18测试用例):
- 1
- 11
- 21
- 1211
- 111221
- 312211
- 13112221
- 1113213211
- 31131211131221
- 13211311123113112211
- 11131221133112132113212221
- 3113112221232112111312211312113211
- 1321132132111213122112311311222113111221131221
- 11131221131211131231121113112221121321132132211331222113112211
- 311311222113111231131112132112311321322112111312211312111322212311322113212221
时间复杂度:O(???)
空间复杂度:O(n)(结果字符串长度)
1 class Solution
2 {
3 public:
4 string countAndSay(int n)
5 {
6 string s = "1";
7 for(int i = 1; i < n; ++ i)
8 {
9 int count = 1;
10 string temp = "";
11 for(int j = 1; j < s.size(); ++ j)
12 {
13 if(s[j] == s[j - 1])
14 ++ count;
15 else
16 {
17 temp = temp + (char)(count + ‘0‘) + s[j - 1];
18 count = 1;
19 }
20 }
21 s = temp + (char)(count + ‘0‘) + s[s.size() - 1];
22 }
23 return s;
24 }
25 };
或者
1 class Solution
2 {
3 public:
4 string countAndSay(int n)
5 {
6 string s = "1";
7 for(int i = 1; i < n; ++ i)
8 {
9 string temp = "";
10 for(int j = 0, count; j < s.size(); ++ j)
11 {
12 for(count = 1; j < s.size() && s[j] == s[j + 1]; ++ j, ++ count);
13 temp = temp + (char)(count + ‘0‘) + s[j];
14 }
15 s = temp;
16 }
17 return s;
18 }
19 };