LeetCode/solutions/38. Count and Say.md
2019-09-13 23:08:41 +08:00

1.1 KiB
Raw Blame History

38. Count and Say

思路

首先要搞清楚题目意思,初试串为"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; 
    }
};