LeetCode HOT100 - 字符串解码
感觉和括号或者计算式子比较像
因此用栈去模拟
每次碰到 ']' ,就处理好这个 '[' ']' 包裹的式子
处理好后仍然放到栈中,因为可能会被更大的 '[' ']' 包裹
整体就是模拟
class Solution {
public:
string decodeString(string s) {
vector<char> st;
for (char c : s) {
if (c != ']') {
st.push_back(c);
} else {
string tmp;
while (!st.empty() && st.back() != '[') {
tmp = st.back() + tmp;
st.pop_back();
}
st.pop_back();
int num = 0, base = 1;
while (!st.empty() && isdigit(st.back())) {
num += (st.back() - '0') * base;
base *= 10;
st.pop_back();
}
for (int i = 0; i < num; i++) {
for (char ch : tmp) {
st.push_back(ch);
}
}
}
}
return string(st.begin(), st.end());
}
};

浙公网安备 33010602011771号