[LeetCode]38. Count and Say
程序员文章站
2022-03-23 18:31:41
...
[LeetCode]38. Count and Say
题目描述
思路
字符串拼接,暴力遍历即可
代码
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
if (n == 0)
return "";
string res = "1";
while (--n) {
string cur = "";
for (int i = 0; i < res.size(); ++i) {
int count = 1;
while (i + 1 < res.size() && res[i] == res[i + 1]) {
++count;
++i;
}
cur += to_string(count) + res[i];
}
res = cur;
}
return res;
}
};
int main() {
Solution s;
cout << s.countAndSay(5) << endl;
system("pause");
return 0;
}