码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode - 38. Count and Say

时间:2016-05-07 08:29:36      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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.

Leetcode - 38. Count and Say

标签:

原文地址:http://blog.csdn.net/noshandow/article/details/51335093

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!