LeetCode 0038 - Count and Say
# Hints
- 模拟
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Easy |
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 where $ 1 \le n \le 30$ , generate the -th 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"
# 题意
详见题面,懒得写了,太麻烦了。
# 题解
水题,按题意模拟即可。
# AC代码
class Solution {
public:
string countAndSay(int n) {
// 求解
string res = "1";
for (int t = 1; t <= n - 1; t ++) {
string str;
char ch = res[0];
int cnt = 1;
for (int i = 1; i < res.length(); i ++) {
if (res[i] == ch) {
cnt ++;
} else {
// 更新答案
str += to_string(cnt);
str += ch;
// 重置
ch = res[i];
cnt = 1;
}
}
// 更新答案
str += to_string(cnt);
str += ch;
res = str;
}
// 返回
return res;
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01