2018-10-07 15:31:56 +00:00
|
|
|
|
# [38. Count and Say](https://leetcode.com/problems/count-and-say/description/)
|
|
|
|
|
# 思路
|
|
|
|
|
首先要搞清楚题目意思,初试串为"1",按照数数的规则产生后面的序列:
|
|
|
|
|
* 第1个字符串为"1", 即1个1,所以第2个字符串为"11";
|
|
|
|
|
* 第2个字符串为"11", 即2个1,所以第3个字符串为"21";
|
|
|
|
|
* 第3个字符串为"21", 即1个2和1个1,所以第4个字符串为"1211";
|
|
|
|
|
* 第4个字符串为"1211", 即1个1、1个2和2个1,所以第2个字符串为"111221";
|
|
|
|
|
* ......
|
|
|
|
|
|
|
|
|
|
搞懂意思后,按照规则模拟即可。
|
|
|
|
|
# C++
|
2019-09-13 15:08:41 +00:00
|
|
|
|
``` C++
|
2018-10-07 15:31:56 +00:00
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
string countAndSay(int n) {
|
|
|
|
|
string res = "1";
|
|
|
|
|
while(n-- > 1){ // 循环产生第n个串
|
|
|
|
|
string tmp;
|
|
|
|
|
int low=0, high=1;
|
|
|
|
|
while(low < res.size()){
|
|
|
|
|
while(high < res.size() && res[high] == res[low]) high++;
|
|
|
|
|
tmp += (high - low + '0');
|
|
|
|
|
tmp += res[low];
|
|
|
|
|
low = high;
|
|
|
|
|
high++;
|
|
|
|
|
}
|
|
|
|
|
res = tmp;
|
|
|
|
|
}
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|