38. Count and Say
Difficulty: Easy
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.
序列1, 11, 21, 1211, 111221, 312211, …,给的整数n,返回序列的第n个字符串。
1 “one 1”—-11 “two 1” —-21 “one 2 one 1” —- 1211 …
class Solution {
public:
string countAndSay(int n) {
string str = "1";
string nstr;
if (n == 1)
{
return str;
}
int count;
int k = 1;
while (k < n)
{
count = 0;
int sub = 0;
int size = str.size();
nstr = "";
for (int i = 0; i < size; i++)
{
if (str[i] == str[sub]) //若是相同的字符,记录次数
{
count++;
}
else //若与上一个字符不同
{
nstr += count + '0'; //数字+'0'得到对应的字符
nstr += str[sub];
sub = i;
count = 1; //count=1,因为当前字符已出现一次
}
}
nstr += count + '0'; //最后一个字符
nstr += str[size-1];
k++;
str = nstr;
}
return str;
}
};
数字+’0’得到对应的字符。
1.string类库
string str;
str.size()获得字符串的大小。不以‘\0’为结束标志
赋值时不能逐个字符赋值,
str[num++]=count+'0'; str[num++]=str[sub]; //**是错误的**
2.C风格字符串
char *ch;
strlen(ch)获得字符串的大小。以‘\0’为结束标志
赋值时只能逐个字符赋值,
ch[i]='a'; //是正确的