Leetcode - 38. Count and Say

38. Count and Say

题目简介

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.s

解法一:迭代

思路如下:遍历前一个字符串的字符,若上一个字符和当前字符相等就自增加计数,否则输出到res中并且初始化计数器。

此种方法同前面去除数组中相同的元素。

string countAndSay(int n) {
        if(n==0) return "";

        string prev = "1";
        string res = "";
        int count=1;
        for(int i=1;i<n;i++){
            for(int j=1;j<=prev.length();j++){
                if(j==prev.length()){
                    cout<<i<<": "<<prev[j]<<endl;
                }
                if(prev[j-1]==prev[j]){
                    count++;
                }else{
                    res += to_string(count);
                    res += prev[j-1];
                    count = 1;
                }
            }

            prev = res;
            res = "";
            /* ~~My Own Stupid Code ~~s
            ch = prev[0];
            count = 1;
            for(int j=1;j<prev.length();j++){
                while(ch==prev[j]){
                    count++;
                    j++;
                }
                res += count;
                res += ch;
                ch = prev[j];
                count = 1;
            }
            prev = res;
            res = "";
            cout<<i+1<<" "<<res;
            */
        }

        return prev;
    }

解法二:递归

 string countAndSay(int n) {
      if(n==1) return "1";

      string prev = countAndSay(n-1);
      int left = 0;
      int right = 0;
      string res = "";

      while(left<prev.length()){
          while(prev[left]==prev[right]) right++;
          res += to_string(right-left)+ prev[left];
          left = right;
      }

      return res;
    }s

总结

起初我在思考这个问题的时候,并没有想到递归,使用递归将会简化代码,更好的理解。

在使用迭代方法时,有以下一些注意事项:
1. 注意边界值
- 遍历次数从1到n-1: int i=1;i<n;i++
- 每个字符串遍历: for(int j=1;j<=prev.length();j++) ;
- 对于字符串的prev[length]为\0
2. 不需要单独定义一个char存储当前字符
3. 逻辑很简单,simple is better.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值