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 {
/*思想很简单,用两个vector,每次将cur赋值给pre避免了每次判断cur pre的情况处理。主要问题在于处理最后一个元素,判断数组是否溢出。
解决的方法为添加一个哨兵,或者每次取元素之前判断下标。
需要注意的情况是 ++i和i++。一个是确定与前一个元素不同之后,处理这个元素。后者为确定与前一个元素不同之后,处理下一个元素(不正确)*/
public:
string countAndSay(int n) {
vector<char> pre;
vector<char> cur;
pre.push_back('1');
cur.push_back('1');
int i=1;
while(i<n){
cur.clear();
int len=pre.size();
// pre.push_back(-1);
for(int i=0;i<len;){
int count=1;
int temp=pre[i];
while(++i<len&&temp==pre[i]) count++;
cur.push_back('0'+count);
cur.push_back(pre[i-1]);
}
pre=cur;
i++;
}
string re="";
for(vector<char>::iterator iter=cur.begin();iter!=cur.end();iter++){
re+=*iter;
}
return re;
}
};