标签:strong term rom public 输出 int length vector sequence
38. Count and Say
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
6. 312211
7. 13112221
8. 1113213211
解题思路:
1)输入n为0和1时,分别输出相应的值;
2)输入n大于1时,分别判断相连的3个数或者相连的2个数是否相同,若相同输出对应的值,若不同,则输出1加上该数
代码如下:
class Solution {
public:
string countAndSay(int n) {
vector<string> str(n);
if(n==0)
return "";
else if(n==1)
return "1";
else{
str[0]="1";
for(int i=0;i<n-1;i++){
int length=str[i].size();
str[i+1]="";
int j=0;
string temp;
while(j<length){
if( j+2<length && str[i][j]==str[i][j+1] && str[i][j]==str[i][j+2] ){
temp=to_string(3)+str[i][j];
j=j+3;
}
else if(j+1<length && str[i][j]==str[i][j+1] ){
temp= to_string(2)+str[i][j];
j=j+2;
}
else{
temp= to_string(1)+str[i][j];
j=j+1;
}
str[i+1]=str[i+1]+temp;
}
}
return str[n-1];
}
}
};
LeeCode from 0 ——38. Count and Say
标签:strong term rom public 输出 int length vector sequence
原文地址:https://www.cnblogs.com/ssml/p/9182164.html