题目:
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.
题目描述不清, WA 了一次
Input:6 Output:"21112211" Expected:"312211"
思路:
1. 计数, 前进
代码:
class Solution { public: string countAndSay(int n) { string prestr = "1", curstr; if(n == 1) return prestr; for(int i = 1; i < n; i ++) { curstr = generateNext(prestr); prestr = curstr; } return curstr; } string generateNext(const string &prestr) { string str; for(int i = 0; i < prestr.size(); i ++) { int n = countSame(prestr, i); str.push_back(n+'0'); str.push_back(prestr[i]); i += n-1; } return str; } int countSame(const string &prestr, int i) { if(i >= prestr.size()) return 0; int cnt = 1, prechar = prestr[i]; i++; while(i < prestr.size()) { if(prestr[i] == prechar) { cnt++; i++; }else{ return cnt; } } return cnt; } };