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 = “1”,从1开始往后的字符串都是指前面一个字符串按顺序出现的值得计数形式。
python:
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = "1"
if n == 1:
return res
for i in range(1,n):
j = 0
count = 1
temp = ""
while j < len(res):
s = res[j]
if j == len(res) - 1:
temp += str(count)
temp += s
break
if res[j] == res[j+1]:
count += 1
j += 1
else:
temp += str(count)
temp += s
count = 1
j += 1
res = temp
return res
C++:
class Solution {
public:
string countAndSay(int n) {
string res = "1";
if(n == 1) return res;
for(int i = 1;i < n;i++){
int j = 0;
int count = 1;
string temp;
while(j < res.length()){
char s(res[j]);
if(j == res.length() - 1){
temp += to_string(count);
temp += s;
break;
}
if(res[j+1] == res[j]){
count += 1;
j += 1;
}
else{
temp += to_string(count);
temp += s;
count = 1;
j += 1;
}
}
res = temp;
}
return res;
}
};