class Solution {
public:
string countAndSay(int n) {
string s = "1";
for (int ii = 0; ii < n-1; ++ii) {
s = getNext(s);
}
return s;
}
string getNext(string s) {
string say = "";
for(int ii = 0; ii < s.size(); ++ii) {
int repeat = countRepeat(s, ii);
say.push_back(repeat + '0');
say.push_back(s[ii]);
ii += repeat-1;
}
return say;
}
unsigned int countRepeat(string s, unsigned int pos) {
char c = s[pos];
int ii = pos;
for(; ii < s.size(); ++ii){
if (s[ii] != c) break;
}
return ii - pos;
}
};
No comments:
Post a Comment