LeetCode - Count and Say
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.
========================================================
1. Solution 1
class Solution: def countAndSay(self,n): seq = '1' for _ in range(n-1) : seq = self.nextSeq(seq) return seq def nextSeq(self,seq): n = len(seq) i, s = 0, '' while i<n: j = 1 while i<(n-1) and seq[i]==seq[i+1]: j += 1 i += 1 s += str(j) + seq[i] i += 1 return s n = input('Please enter a number:') test = Solution() for i in range(n): i += 1 print i, '.', test.countAndSay(i)
2. Solution 2
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ seq = '1' for _ in range(n-1): length, nextSeq, i = len(seq), '', 0 while i<length: j = 1 while i<(length-1) and seq[i]==seq[i+1]: j += 1 i += 1 nextSeq += str(j) + seq[i] i += 1 seq = nextSeq return seq
n = input('Please enter a number:') test = Solution() for i in range(n): i += 1 print i, '.', test.countAndSay(i)
Refs.
1. https://github.com/kamyu104/LeetCode/blob/master/Python/count-and-say.py
2. https://discuss.leetcode.com/topic/28084/simple-python-solution

浙公网安备 33010602011771号