1. 程式人生 > >LeeCode from 0 ——38. Count and Say

LeeCode from 0 ——38. Count and Say

urn ++ temp ont RM fir IT The family

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