文章目录
更多LeetCode题解
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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: “1”
Example 2:
Input: 4
Output: “1211”
Solution
迭代法可解。
class Solution {
public:
string countAndSay(int n) {
string s1 = "1";
string s2 = "1";
for (int i = 0; i < n-1; i++) {
int count;
s1 = s2;
s2.clear();
for (int j = 0; j <= s1.size(); j++) {
if (j == 0) {
count = 1;
}
else if (j == s1.size()) {
char c_count = count+'0';
s2.push_back(c_count);
s2.push_back(s1[j - 1]);
}
else if (s1[j] != s1[j - 1]) {
char c_count = count+'0';
s2.push_back(c_count);
s2.push_back(s1[j - 1]);
count = 1;
}
else {
count++;
}
}
}
return s2;
}
};