【题目】
Given an encoded string, return it's 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”.
题解
题目的意思是对一个字符串进行解码,比如 3[a] 解码成 aaa。
首先要注意到,输入的[]可能是并排关系,比如2[ab]3[cd]e
,也可能是包含关系2[ab3[cd]e]
。
我的做法是用一个栈存这字符串,遇到]
进行编译。如下:
2[ab]3[cd]e | 2[ab3[cd]e]f | |
---|---|---|
遇到第一个[ | 2,[, a, b, ] | 2, [, a, b, 3, [, c, d, ] |
编译 | abab | 2, [, a, b, cdcdcd |
继续入栈,遇到第二个] | abab, 3, [, c, d, ] | 2, [, a, b, cdcdcd, e, ] |
编译 | abab, cdcdcd | abcdcdcdeabcdcdcde |
··· | ··· | ··· |
最后的栈 | abab, cdcd, e | abcdcdcdeabcdcdcde, f |
连接每一项 | ababcdcde | abcdcdcdeabcdcdcdef |
考虑到数字也有可能是多位数,比如2[a]10[b]
,我也用了一个栈来存放数组
小编本次尝试用C++和javascript两种语言实现这个算法,C++程序跑leetCode给出的27个test使用了3ms,javascript使用了82ms
c++代码
string decodeString(string s) {
stack<string> mystack; // 放字符串
stack<int> nums; // 放数字,数字可能是多位的
string repeat="";
int num;
for(int i=0;i<s.size();i++){
if(s[i]>='0'&&s[i]<='9'){
num = 0;
while(s[i]>='0' && s[i]<='9'){
num = num*10 + s[i] - '0';
i++;
}
i--;
nums.push(num);
}
else if(s[i] == ']'){
string temp = "";
num = nums.top();
nums.pop();
while(mystack.top()!="["){
temp = mystack.top()+temp;
mystack.pop();
}
mystack.pop();
while(num--){
repeat+=temp;
}
mystack.push(repeat);
repeat = "";
}
else{
mystack.push(s.substr(i,1));
}
}
while(!mystack.empty()){
repeat =mystack.top()+repeat;
mystack.pop();
}
return repeat;
}
javascript代码
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
var stack = []; //放字符串
var nums = []; // 放数字,数字可能是多位的。
var result = ""; // 重复的字段
for(var i=0;i<s.length;i++){
if(!isNaN(s[i])){
var num = 0;
while(!isNaN(s[i])){
num = num*10+ Number(s[i]);
i++
}
i--;
nums.push(num);
}
else if(s[i] == ']'){
var temp = '', pop = stack.pop();
num = nums.pop();
while(pop!='['){
temp = pop +temp;
pop = stack.pop();
}
while(num--){
result+=temp;
}
stack.push(result);
result = '';
}
else{
stack.push(s[i]);
}
}
return stack.join('');
};