Loading

38. Count and Say

Count and Say

这一题的难点在于理解题意。

class Solution {
   public:
    string countAndSay(int n) {
        if (n <= 0) {
            return "";
        }
        std::string ret = "1";
        while (--n != 0) {
            std::string current_str;
            for (std::size_t i = 0; i < ret.size(); ++i) {
                std::size_t cnt = 1;
                while (i + 1 < ret.size() && ret[i] == ret[i + 1]) {
                    ++cnt;
                    ++i;
                }
                current_str += (std::to_string(cnt) + ret[i]);
            }
            ret = current_str;
        }
        return ret;
    }
};

输出:

1: "1"
10: "13211311123113112211"

从输出结果看,只有 1, 2, 3 三个数字出现。用反证法可以说明这个问题确实只能出现这三个数字。

假设countAndSay(n)中有数字4,那么第n-1个字符串必定有4个相同的数字,假设这个数字为1,则第n-1个字符串可以设为"x1111y",第n-1个字符串是第n-2个字符串的读法,所以第n-2个字符串可以读为"x个1,1个1,1个y"或者"*个x,1个1,1个1,y个*",这两种读法分别可以合成"x+1个1,1个y""*个x,2个1,y个*"。即第n-1个字符串可以读作"(x+1)11y"或者"x21y"。这都不可能是"x1111y"

posted @ 2020-12-15 20:09  hfang  阅读(69)  评论(0)    收藏  举报