394. Decode String
Problem:
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
复制s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
思路:
Solution (C++):
string decodeString(string s) {
stack<string> ch;
stack<int> nums;
string res = "";
int num = 0;
for (char c : s) {
if (isdigit(c)) {
num = num*10 + c-'0';
}
else if (isalpha(c)) {
res += c;
}
else if (c == '[') {
ch.push(res);
nums.push(num);
res = "";
num = 0;
}
else {
string tmp = res;
for (int i = 0; i < nums.top()-1; ++i) {
res += tmp;
}
res = ch.top() + res;
ch.pop(); nums.pop();
}
}
return res;
}
性能:
Runtime: 0 ms Memory Usage: 6.7 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步