38. Count and Say
Description
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.
Analysis
这道题目的意思我其实一开始没看懂,题意比较模糊,容易导致理解错误。
后来才明白,其实题目的意思就是后一个字符串是前一个字符串中每一个连续一样的数字的数量之和加上数字本身。
例如 s1=”1” 有1个1 。所以s2=”11”,表示有1个1,此时s2有2个1。
所以s3 =”21”,表示有2个1。以此类推,一直这样下去。
我的做法就是利用迭代,每一次将数字,对于当前字符串判断其当前字符是否和前一个字符相等,若相等,则count++;
若不相等,则将count中的数字以及当前字符push进新字符串中,更新pre以及count。
这样得到的新字符串就是我们的结果。
Code
class Solution {
public:
string fun (string s){
string str;
int len = s.size();
char pre = s[0];
int count = 1 ;
for(int i = 1 ;i <len;++i){
if(s[i] == pre) count ++;
else{
//str = str + (count + '0');
char a = '0'+count;
str +=a;
str+=pre;
count =1;
pre = s[i];
}
}
char a = '0'+count;
str +=a;
str+=pre;
return str;
}
string countAndSay(int n) {
if(n == 0) return "";
if(n == 1) return "1";
string s = "1";
int j = 1;
while(j<n){
s = fun(s);
j++;
}
return s;
}
};