Description
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"
分析
题目的意思是:一开始我没读懂题目的意思,其实就是一个数数字的游戏
最开始是1,然后就是一个一,11;然后是两个一,21;然后是一个二一个一,1211…
- 理解题目的意思了,递归就很容易解决这个问题了。
C++代码
class Solution {
public:
string countAndSay(int n) {
string ans;
ans="1";
for(int i=1;i<n;i++){
solve(ans);
}
return ans;
}
void solve(string &ans){
string tmp="";
int count=1;
for(int i=0;i<ans.size();i++){
if(i+1<ans.size()&&ans[i]==ans[i+1]){
count++;
}else{
char ch=count+'0';
tmp=tmp+ch+ans[i];
count=1;
}
}
ans=tmp;
}
};
Python 代码
class Solution:
def solve(self,res):
t=''
count=1
for i in range(len(res)):
if i+1<len(res) and res[i]==res[i+1]:
count+=1
else:
t=t+str(count)+str(res[i])
count=1
return t
def countAndSay(self, n: int) -> str:
res='1'
for i in range(1,n,1):
res=self.solve(res)
return res
下面是另一个版本的代码:
class Solution:
def countAndSay(self, n: int) -> str:
res ='1'
for i in range(n-1):
cur = ""
pos = 0
start = 0
while pos <len(res):
while pos < len(res) and res[pos]==res[start]:
pos+=1
cur += str(pos-start)+res[start]
start = pos
res = cur
return res
参考文献
leetCode 38.Count and Say (计数和发言) 解题思路和方法
[编程题]count-and-say