一、题目说明
题目394. Decode String,给定一个编码后字符串,解码字符串。难度是Medium!
二、我的解答
解析字符串,这个题目是栈的典型应用。唯一的复杂度在于嵌套的处理。
class Solution{
public:
string decodeString(string s){
stack<char> st;
stack<int> st_r;
int repeat = 0,index=0;
string res;
int toStack = 0;
while(index < s.size()){
char c = s[index];
if(c>='0' && c<='9'){
repeat = repeat * 10 + (c -'0');
}else if(c=='['){
st.push(c);
st_r.push(repeat);
repeat = 0;
toStack++;
}else if(c==']'){
string cur;
repeat = st_r.top();
st_r.pop();
while(!st.empty() && st.top()!='['){
cur.push_back(st.top());
st.pop();
}
st.pop();
reverse(cur.begin(),cur.end());
if(toStack > 1){
while(repeat>0){
for(int i=0;i<cur.size();i++){
st.push(cur[i]);
}
repeat--;
}
}else{
while(repeat>0){
res.append(cur);
repeat--;
}
}
toStack--;
}else if(toStack>0){
st.push(c);
}else{
res.push_back(c);
}
index++;
}
return res;
}
};
性能如下:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Decode String.
Memory Usage: 9 MB, less than 58.82% of C++ online submissions for Decode String.
三、优化措施
无