[LeetCode]38. Count and Say

Description

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

Example1:
Input: 1
Output: “1”

Example2:
Input: 4
Output: “1211”

Discussion

第一个数字为“1”,第二个数字是第一个数字的读法“一个1”或“11”,第三个数字是第二个数字的读法“两个1”或“21”,以此类推……

知道了规律后,我们就可以确定算法了。每一个字符串都是根据上一个字符串来生成的。这就转变成了一个计数问题。我们只需要遍历一遍,每次检查当前字符是否和上一个字符相同,相同的话就把计数器加一,不同的话就在新的字符串中添加相应的信息。

算法的时间复杂度为O(n^2)。

C++ Code

class Solution {
public:
    string countAndSay(int n) {
        vector<string> answer;      //保存结果,answer[i-1]保存第i个结果
        answer.push_back("1");
        for(int i = 1; i < n; i++)
        {
            string tmp = answer[i - 1];        //记录上一次的字符串
            string new_answer = "";     //新字符串的结果
            int count = 1;
            for(int j = 1; j <= tmp.length(); j++)
            {
                //遍历到tmp末尾后一个的时候,就把前面的数字加到answer中,并跳出
                if(j == tmp.length())
                {
                    new_answer = new_answer + to_string(count) + tmp[j - 1];
                    break;
                }
                //判断当前字符是否和前一个字符相同,如果相同则计数器加一,否则把前一段相同的字符加入到answer中。
                if(tmp[j] == tmp[j - 1])
                {
                    count ++;
                }
                else
                {
                    new_answer = new_answer + to_string(count) + tmp[j - 1];
                    count = 1;
                }
            }
            answer.push_back(new_answer);
        }
        return answer[n - 1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值