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.

链接:  http://leetcode.com/problems/count-and-say/

一刷。这道题很简单,边界问题缺有点麻烦,其实也不是麻烦,但是思维上有需要改进的地方:

1.外循环几次,N=0和N=1是单独返回的,其实N>1的话,只要计算N-2次就可以了。N的第几个数,而循环则是经过几次处理,两个差了一次遍历

2.每次循环结束时,只考虑了最后一个数字与之前不相等时候需要加到list后面,其实所有情况都需要考虑。只考虑特殊情况是错的!!!

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 0:
            return ''
        if n == 1:
            return '1'
        
        old = '1'
        new = []
        
        for seq in range(n - 1):
            for idx, val in enumerate(old):
                if idx == 0:
                    prev = val
                    count = 1
                else:
                    if val == prev:
                        count += 1
                    else:
                        new.extend([str(count), prev])
                        count = 1
                        prev = val
            else:
                new.extend([str(count), prev])
            old = ''.join(new)
            new = []
        return old

 2/11/2017, Java

犯的错误:

1. StringBuilder初始化用String,不用char,区别是单引号和双引号;

2. 如果不想额外特例判断长度,c和n应该初始化在index = 0的位置;

3. 跳过相同的字符时,一定注意是否越界!

4. ret.append(n-c)这句我不懂;

5. c = n不是c++

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         StringBuilder a = new StringBuilder("1");
 4         for (int i = 0; i < n - 1; i++) {
 5             a = count(a);
 6         }
 7         return a.toString();
 8     }
 9     StringBuilder count(StringBuilder s) {
10         StringBuilder ret = new StringBuilder();
11         int c = 0;
12         int n = 0;
13         while (n < s.length()) {
14             while (n < s.length() && s.charAt(n) == s.charAt(c)) n++;
15             ret.append((n - c));
16             ret.append(s.charAt(c));
17             c = n;
18         }
19         return ret;
20     }
21 }

 

posted @ 2016-06-12 09:46  panini  阅读(138)  评论(0编辑  收藏  举报