Leetcode 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.

从‘1’生成n-1次就可以得到第n个字符串。

双指针,j表示原来的数,i扫描之后的数,发现若不一样则新字符串增加'(i-j)'+s[j],然后 j=i。

这里使用'#'来表示字符串结束。

def count_and_say(n)
  return '1' if n == 1
  s0 = '1'
  (n-1).times do
    s0 += '#'
    j, s1 = 0, ''
    s0.length.times do |i|
      if s0[i] != s0[j]
        s1 += (i-j).to_s + s0[j]
        j = i
      end
    end
    s0 = s1
  end
  s0
end

 单纯的模拟

class Solution(object):
    def countAndSay(self, n):
        s, ans = '1', '1'
        for x in range(n-1):
            ans = ''
            s += '#'
            count = 1
            for i in range(1,len(s)):
                if s[i] == s[i-1]:
                    count += 1
                else:
                    ans += str(count) + s[i-1]
                    count = 1
            s = ans
        return ans
posted @ 2015-06-14 13:04  lilixu  阅读(153)  评论(0编辑  收藏  举报