LeetCode/solutions/38. Count and Say.md

33 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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++
```
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;
}
};
```