Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/# Count and Say
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
58 lines (45 sloc)
1.29 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is not a difficult problem. However, it's very hard to understand what's the meaning of it. | |
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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. | |
Note: Each term of the sequence of integers will be represented as a string. | |
Example 1: | |
Input: 1 | |
Output: "1" | |
Example 2: | |
Input: 4 | |
Output: "1211" | |
My code: | |
class Solution: | |
def countAndSay(self, n): | |
""" | |
:type n: int | |
:rtype: str | |
""" | |
#The idea is n is to explain the result of n-1 | |
if n==1: | |
return '1' | |
res=self.countAndSay(n-1) | |
i=0 | |
new_res="" | |
while i<len(res): | |
result_now=res[i] | |
k=0 | |
while i+k<len(res): | |
if res[i+k]==result_now: | |
k=k+1 | |
else: | |
break | |
count=k | |
new_res=new_res+str(count)+str(result_now) | |
i=i+count | |
return new_res | |
Solution: | |
https://leetcode.com/problems/count-and-say/ |