题目链接:https://leetcode.com/problems/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.
解析:模拟即可。
n=1 数列为 1
n=2 数列为11
n=3 数列为21
n=4 数列为1211
n=5 数列为111221
当n=2的时候我们可以看数列1 都有哪些数字,n=3的时候我们看数列2都有哪些数字,这样一次次的模拟即可。
利用两个临时string,如此反复。
string countAndSay(int n) {
if (n == 0) return "";
string str = "1";
for (int i = 1; i<n; ++i){
char ch = '0';
string str2 = "";
int counting = 0;
for (int j = 0; j<str.length(); ++j){
if (str[j] == ch) counting++;
else{
if (counting>0)
str2 = str2 + char(counting + '0') + ch;
counting = 1;
ch = str[j];
}
}
str2 = str2 + char(counting + '0') + ch;
str = str2;
}
return str;
}
假设n = 4 数列为1211 我们现在要求n=5的数列。
我们就可以根据 1211 来模拟。
第一步:初始的时候,我们遍历到当前的字符时,如果跟上一个字符不相同,则对str2赋值,str2=str2+char(counting+'0')+chl,并对新的数字重新计算counting = 1,ch=str[j]。
如果当前的字符与上一个相同,那么使counting++。
当这一次遍历结束时,把值赋给str,并进行继续循环 求下一个n。