【 关关的刷题日记47】Leetcode 38. Count and Say

时间:2022-05-08
本文章向大家介绍【 关关的刷题日记47】Leetcode 38. Count and Say,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记47 – Leetcode 38. Count and Say

题目

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1 Output: "1" Example 2:

Input: 4 Output: "1211"

题目的意思:将由数字构成的字符串读出来成为一个新的字符串。比如1口语是1个1,记作11;11读作2个1,记作21;21读作1个2,1个1,记作1211……。输入n,计算第n个这样的数字。

思路

思路:按照将字符串读出来成为一个新的字符串的思路来暴力求解。

class Solution {
public:
    string countAndSay(int n) {
        if(n==0)
            return "";
        if(n==1)
            return "1";
        string s="1";
        for(int i=1; i<n; i++)
        {
            int count=1;
            string temp="";
            for(int i=0; i< s.size()-1; i++)
            {
                if(s[i+1]==s[i])
                    ++count;
                else
                {
                    temp=temp+char(count+'0')+s[i];
                    count=1;
                }  
            }
            s=temp+char(count+'0')+s[s.size()-1];
        }
        return s;
    }
};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。