LeetCode——报数

 

 string countAndSay(int n)
    {
        string str = "1";
        for (int i = 1; i < n; ++i)
        {
            string str_new{""};
            for (int j = 0, count = 1; j < str.size(); j++, count = 1)
            {
                while (str[j + 1] == str[j])//说明①
                {
                    count++;
                    j++;
                }
                str_new += to_string(count);
                str_new += str[j];
            }
            str = str_new;
        }
        return str;
    }

说明①:

此处原代码为

 while (j + 1 < str.size() & str[j + 1] == str[j])

后阅读其他人的代码后,注意到string最后一位是"/0",在VS上测试程序也可以通过【但debug中str[str.size()]处确实越界了】。

便简化了代码。

猜你喜欢

转载自blog.csdn.net/goldcarpenter/article/details/82915326
今日推荐