Count and Say - LeetCode

题目链接

Count and Say - LeetCode

注意点

  • 输入的序列可能小于等于0

解法

解法一:观察题目给的序列,加上网上的评论,可以看出从第二个序列开始,每个序列是对前一个序列的报数。例如,前一个序列是1211,那下一个序列就是1个1、1个2、2个1 = 111221。也就是说每个序列的各个数字之间省略了“个”字。时间复杂度为O(n)

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

小结

  • 这道题真的是考验语文功底。。。

猜你喜欢

转载自www.cnblogs.com/multhree/p/10352498.html