题目
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.
思路
好几题没刷leetcode手痒痒,又没太多时间,就选了个Easy的题啦…这个题目确实挺简单的,统计一下前面是不是重复就行了。在句末加一个特殊符号可以避免多写几行代码的样子~
代码
class Solution { public: string countAndSay(int n) { string nStr = "1$"; string nextStr = ""; while(n > 1){ char lastChr = '$'; int lastCount = 0; for(int i=0; i<nStr.size(); i++){ if(nStr[i] == lastChr){ lastCount++; } else { if(lastCount > 0){ string tempStr; while(lastCount > 0){ tempStr += (lastCount%10 +'0'); lastCount /= 10; } reverse(tempStr.begin(), tempStr.end()); nextStr += tempStr; nextStr += lastChr; } lastCount = 1; lastChr = nStr[i]; } } nStr = nextStr + "$"; nextStr = ""; n--; } return nStr.substr(0, nStr.size()-1); } };