要求:输入:s = “3[a2[c]]”,输出:“accaccacc”
思路:本题分两种情况,遇到字母或者数字[字母,注意考虑是否在嵌套下。流水线式代码。。时间100%
class Solution {
public:
//3[a2[c2[d]e]],栈不空的话弹出来要加栈顶
string decodeString(string s) {
int n=s.length();
stack<int> si;
stack<string> st;
string ans;
int i=0;
while(i<n){
int num=0;
string tmp;
if(s[i]>='a'&&s[i]<='z'){//遇到字母只匹配掉字母
while(i<n&&s[i]>='a'&&s[i]<='z'){
tmp+=s[i];
++i;
}
if(!st.empty()){//栈不空说明处在嵌套加入栈顶
tmp=st.top()+tmp;
st.pop();
st.push(tmp);
}
else ans+=tmp;//栈空直接拼接
}
else if(s[i]>='0'&&s[i]<='9'){//遇到数字直接匹配掉对应的字母...
while(i<n&&s[i]>='0'&&s[i]<='9'){
num=num*10+s[i]-'0';
++i;
}
++i;//跳过'['
while(i<n&&s[i]>='a'&&s[i]<='z'){//匹配掉字母
tmp+=s[i];
++i;
}
if(s[i]==']'){//这是一个完整串3[ac]
++i;
string ttmp=tmp;
while(--num)tmp+=ttmp;
if(!st.empty()){//栈不空说明处在嵌套加入栈顶
tmp=st.top()+tmp;
st.pop();
st.push(tmp);
}
else ans+=tmp;//栈空直接拼接
}
else {//这个串不完整那暂时先压栈
si.push(num);
st.push(tmp);
}
}
else{//遇到']'则出栈合并嵌套
++i;
tmp=st.top();
string ttmp=tmp;
num=si.top();
while(--num)tmp+=ttmp;
st.pop();
si.pop();
if(!st.empty()){//还在嵌套再加栈顶
tmp=st.top()+tmp;
st.pop();
st.push(tmp);
}
else ans+=tmp;//直接拼接
}
}
return ans;
}
};
法二:递归,以[]作为分界,处理完嵌套后更新下标,copy了一份
class Solution {
public:
string decodeString(string s) {
return decodeString(s, 0).first;
}
pair<string, int> decodeString(string s, int cur) {
int k = 0;
string decoded;
while (cur < s.size()) {
// 收集数字
if (isdigit(s[cur])) {
k = k * 10 + s[cur] - '0';
cur++;
}
// 收集字母
else if (isalpha(s[cur])) {
decoded.push_back(s[cur]);
cur++;
}
// 开始解析下一层嵌套
else if (s[cur] == '[') {
pair<string, int> res = decodeString(s, cur + 1);
// 解析完嵌套模式后
while (k-- > 0) {
decoded.append(res.first);
}
k = 0;
cur = res.second;
}
// 结束当前递归
else if (s[cur] == ']') {
return {decoded, cur + 1};
}
}
return {decoded, -1};
}
};