标签:
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.s
思路如下:遍历前一个字符串的字符,若上一个字符和当前字符相等就自增加计数,否则输出到res中并且初始化计数器。
此种方法同前面去除数组中相同的元素。
string countAndSay(int n) {
if(n==0) return "";
string prev = "1";
string res = "";
int count=1;
for(int i=1;i<n;i++){
for(int j=1;j<=prev.length();j++){
if(j==prev.length()){
cout<<i<<": "<<prev[j]<<endl;
}
if(prev[j-1]==prev[j]){
count++;
}else{
res += to_string(count);
res += prev[j-1];
count = 1;
}
}
prev = res;
res = "";
/* ~~My Own Stupid Code ~~s
ch = prev[0];
count = 1;
for(int j=1;j<prev.length();j++){
while(ch==prev[j]){
count++;
j++;
}
res += count;
res += ch;
ch = prev[j];
count = 1;
}
prev = res;
res = "";
cout<<i+1<<" "<<res;
*/
}
return prev;
}
string countAndSay(int n) {
if(n==1) return "1";
string prev = countAndSay(n-1);
int left = 0;
int right = 0;
string res = "";
while(left<prev.length()){
while(prev[left]==prev[right]) right++;
res += to_string(right-left)+ prev[left];
left = right;
}
return res;
}s
起初我在思考这个问题的时候,并没有想到递归,使用递归将会简化代码,更好的理解。
在使用迭代方法时,有以下一些注意事项:
1. 注意边界值
- 遍历次数从1到n-1: int i=1;i<n;i++
;
- 每个字符串遍历: for(int j=1;j<=prev.length();j++)
;
- 对于字符串的prev[length]为\0
2. 不需要单独定义一个char存储当前字符
3. 逻辑很简单,simple is better.
标签:
原文地址:http://blog.csdn.net/noshandow/article/details/51335093