【LeetCode】38. Count and Say
Count and Say
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.
思路:对于下一个字符串= 对于当前字符串:∑(字符个数+字符)
例如1211,下一个字符串就是count(1)+'1'+count(2)+'2'+count(1)+'1'=111221
class Solution { public: string countAndSay(int n) { string ret = "1"; if(n == 1) return ret; n --; while(n --) { string next; char last = ret[0]; int i = 1; int count = 1; while(i < ret.size()) { while(i < ret.size() && ret[i] == last) { i ++; count ++; } if(i < ret.size() && ret[i] != last) { next += to_string(count); next += last; count = 1; last = ret[i]; i ++; } } //i == ret.size() next += to_string(count); next += last; ret = next; } return ret; } };