您的位置:首页 > 其它

【Leetcode】Count and Say

2014-07-14 13:11 295 查看
【题目】

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.
【代码】

class Solution {
public:
string countAndSay(int n) {
if(n<=0) return "";
string str="1";         //str用来保存前一个状态的字符串
while(--n){
int count=1;
string newStr="";
for(int i=0;i<str.length();++i){
if((i<str.length()-1)&&(str[i+1]==str[i])) ++count;
else{
char cTemp=(char)(count+'0');
newStr+=cTemp;
newStr+=str[i];
count=1;
}
}
str=newStr;
}
return str;
}
};


【总结】

1.思路:题目的意思是数字符个数然后说出来,每个字符的表达格式是:字符个数+字符本身。对于一个字符串,顺序扫描,统计个数,生成新的表达字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode