LeetCode-探索-初级算法-字符串-8. 报数(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-字符串-8. 报数(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. 报数
  • 语言:C++

  • 思路:题目压根没看懂什么意思,这题就不管了。

  • 参考代码1(8ms):

    https://blog.csdn.net/weixin_39139505/article/details/88928778

    class Solution {
    public:
        string countAndSay(int n) {
            if(n==1) return "1";
            string strlast=countAndSay(n-1);
            int count = 1;//计数
            string res;//存放结果
            for(int i=0;i<strlast.size();i++)
            {
                if(strlast[i]==strlast[i+1])//计算有多少个相同数字
                {
                    count++;
                    continue;
                }
                else
                {
                    if(strlast[i]!=strlast[i+1])
                    {
                        res+=to_string(count)+strlast[i];
                        count=1;
                    }
                }
            }
           return res;
        }
    };
    
  • 参考代码2(0ms):

    class Solution {
    public:
        string countAndSay(int n) {
            string num = "1";
            while (n-- > 1) {
                int count = 1;
                string replace = "";
                for (int i = 0; i < num.length(); i++) {
                    if (num[i] == num[i+1]) {
                        count++;
                        continue;
                    }
                    replace += count + '0';
                    replace += num[i];
                    count = 1;
                }
                num = replace;
            }
            return num;
        }
    };
    
发布了60 篇原创文章 · 获赞 6 · 访问量 5546

猜你喜欢

转载自blog.csdn.net/Ashiamd/article/details/102262786