力扣题:数字与字符串间转换-12.18

发布时间:2023年12月18日

力扣题-12.18

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:38. 外观数列

解题思想:进行遍历然后对字符进行描述即可

在这里插入图片描述

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """

        if n==1:
            return "1"
        temp = "1"
        for i in range(n-1):
            current = ""
            temp_num = temp[0]
            count = 1
            for j in range(1,len(temp)):
                if temp[j] == temp_num:
                    count +=1
                else:
                    current = current+str(count)+str(temp_num)
                    temp_num = temp[j]
                    count = 1
            current = current+str(count)+str(temp_num)
            print(current)
            temp = current
        return current
class Solution {
public:
    string countAndSay(int n) {
        if (n == 1) {
            return "1";
        }

        std::string temp = "1";
        for (int i = 0; i < n - 1; ++i) {
            std::string current = "";
            char temp_num = temp[0];
            int count = 1;

            for (int j = 1; j < temp.length(); ++j) {
                if (temp[j] == temp_num) {
                    count += 1;
                } else {
                    current += std::to_string(count) + temp_num;
                    temp_num = temp[j];
                    count = 1;
                }
            }

            current += std::to_string(count) + temp_num;
            std::cout << current << std::endl;
            temp = current;
        }

        return temp;
    }
};
文章来源:https://blog.csdn.net/yumeng3866/article/details/134940835
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。