Skip to content

Latest commit

 

History

History
32 lines (31 loc) · 1.06 KB

38. Count and Say.md

File metadata and controls

32 lines (31 loc) · 1.06 KB

思路

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