Description:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
看官方的题目描述并没有看懂,原谅我渣渣的英语。搜到了中文的题目描述:
n==1 时,string==“1”;//字符串读1个1
n==2时,string=="11"; //n==2的字符串由n==1时确定,因为n==1时string==“1”读1个1,所以n==2时string==“11”
n==3时,string==“21”;//n==3的字符串由n==2时确定,“11”读作2个1,所以n==3,string=="21"
n==4时,string=="1211"
当给定一个数字n,要求出它对应的string值。
自己的代码如下:
class Solution {
public:
string countAndSay(int n) {
string str;
string tem = "1";
stack<char> stk;
int num=0;
if(n==1)
return "1";
else
str = "1";
for(int i=2; i<=n; i++){
str = tem;
tem="";
for(int j=0; j<str.size(); j++){
if(stk.empty() && j==str.size()-1){
tem = tem + "1"+str[j];
}
else if(stk.empty()){
stk.push(str[j]);
}
else{
if(str[j]==stk.top() && j==str.size()-1){
stk.push(str[j]);
while(!stk.empty()){
stk.pop();
num++;
}
tem = tem + to_string(num) + str[j-1];
num = 0;
}
else if(str[j]==stk.top()){
stk.push(str[j]);
}
else{
while(!stk.empty()){
stk.pop();
num++;
}
if(j==str.size()-1){
tem = tem + to_string(num) + str[j-1] + "1" + str[j];
num = 0;
}
else{
tem = tem + to_string(num) + str[j-1];
stk.push(str[j]);
num = 0;
}
}
}
}
}
return tem;
}
};
写的很啰嗦,用的堆栈,思路如下:
1.堆栈为空就压栈
2.堆栈不为空则比较字符串当前元素与栈顶值是否相同;相同则当前值压栈,不同则对堆栈进行出栈操作,统计出栈的元素个数,并更新暂存的字符串
3.重复1.2.
自己的代码写的很啰嗦,比较了下人家的代码,没有用堆栈,写的很简洁,自己则用了太多的ifelse去处理特殊条件
class Solution {
public:
string countAndSay(int n) {
string prev="11";
string curr="";
if(n==0) return "";
if(n==1) return "1";
if(n==2) return "11";
int i=3;
while(i<=n){
int j=0;
while(j<prev.length()){
int count=1;
while(prev[j+1]!=NULL&&prev[j]==prev[j+1]){
count++;j++;
}
curr+=to_string(count);curr+=prev[j];j++;
}
prev=curr;
curr="";
i++;
}
return prev;
}
};