LeetCode394:字符串解码
作者:互联网
题解:
class Solution {
public:
string decodeString(string s) {
string res = "";
stack<string> strs;
stack<int> nums;
int num = 0;
int n = s.size();
for (int i = 0; i < n; i++) {
if (s[i] >= '0' && s[i] <= '9') {
num = num * 10 + s[i] - '0';
} else if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
res = res + s[i];
} else if (s[i] == '[') {
// 遇见[,则将前面的str加入strs中。并将数字加入nums里面
nums.push(num);
num = 0;
strs.push(res);
res = "";
} else {
// 遇见],则开始累加str。此时的str为从[开始,到]的字符串
int times = nums.top();
nums.pop();
for (int j = 0; j < times; j++) {
strs.top() += res;
}
res = strs.top(); // 更新res
strs.pop();
}
}
return res;
}
};
标签:string,nums,LeetCode394,题解,解码,int,&&,字符串,stack 来源: https://blog.csdn.net/wwwsctvcom/article/details/122163039