力扣 hot100 Day61 - 实践
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string]
,表示其中方括号内部的 encoded_string
正好重复 k
次。注意 k
保证为正整数。
你可以认为输入字符串总是有用的;输入字符串中没有额外的空格,且输入的方括号总符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k
,例如不会出现像 3a
或 2[4]
的输入。
//抄的
class Solution {
public:
string decodeString(string s) {
stack charStack;
stack numStack;
string currentStr;
int currentNum = 0;
for (char c : s) {
if (isdigit(c)) {
currentNum = currentNum * 10 + (c - '0');
} else if (c == '[') {
numStack.push(currentNum);
charStack.push(currentStr);
currentNum = 0;
currentStr.clear();
} else if (c == ']') {
int num = numStack.top();
numStack.pop();
string prevStr = charStack.top();
charStack.pop();
string temp;
for (int i = 0; i < num; i++) {
temp += currentStr;
}
currentStr = prevStr + temp;
} else {
currentStr += c;
}
}
return currentStr;
}
};
实现逻辑其实没啥太复杂的东西,但就是写不出来
从头开始判定字符串,如果是数字,迭代保存记录,如果是左括号,存入数字栈和字母栈,如果是字母,加入currentstr变量中,假如是右括号,弹出数字栈和字母栈,循环拼装成currentstr
其实字母栈中,抛开“”,最多就两个元素,后面会不断根据数字栈元素来更新这两个字母元素