您的位置:首页 > 编程语言 > C语言/C++

leetcode #38 in cpp

2016-05-26 05:31 232 查看
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.
Solution: 

for 1 to n: 

Set current string = "";

Given a string, count the frequency of every unique number. Then append the (frequency in string) + (the number in string) to current string.  

Code: 

class Solution {
public:
string countAndSay(int n) {
string s = "1";

return count_and_say(s,n);
}
string count_and_say(string s, int n){
if(n == 1) return s;
vector<int> count;//count the frequencies of the unique numbers
vector<char> real_num;//record the unique numbers in the string
int temp_count = 0;
for(int i = 0; i < s.length(); i ++){
if(i==0 || s[i] == s[i-1]) temp_count ++;//if the same or it is the head of the string, count + 1
else{
count.push_back(temp_count);//if not the same, we are done with this number.record its count
real_num.push_back(s[i-1]);//record this number
temp_count = 1;
}
}
count.push_back(temp_count);
real_num.push_back(s[s.length() - 1]);
string res = "";
for(int i = 0; i < count.size(); i++){
res += '0' + count[i];//say count first
res += real_num[i];//say the number
}
return count_and_say(res,n-1);

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode