Description
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".
分析
题目的意思是:给你一个string,要求你按照规则解码这个string。
- 这是一个递归的解法。
- 首先如果是字母的话,我们就直接加入res中,如果不是,那就可能是数字,左中括号。
- 如果是数字,我们先计算出数字的值,数字之后必然是左中括号,然后我们跳过它,去递归解码左中括号里面的串,递归回来后。
- 我们分析一下返回条件,要么是到了s的末尾,要么就是遇见右中括号了,于是我们i++,即要么跳过右中括号,要么就到末尾了,然后把t*count倍的字符串加入res中。
C++实现
public:
string decodeString(string s) {
int i=0;
return decode(s,i);
}
string decode(string s,int &i){
int n=s.length();
string res="";
while(i<n&&s[i]!=']'){
if(s[i]<'0'||s[i]>'9'){
res+=s[i];
i++;
}else{
int count=0;
while(s[i]>='0'&&s[i]<='9'){
count=count*10+s[i]-'0';
i++;
}
i++;
string t=decode(s,i);
i++;
while(count--){
res+=t;
}
}
}
return res;
}
};
Python实现
上面的解法很可能把自己绕晕,不容易理解,下面来一个简单易懂的栈方法。
这段代码首先定义了一个栈 stack 以及两个变量 cur_num 和 cur_str,用于跟踪当前的数字和字符串。然后,遍历输入字符串 s 中的每个字符,根据字符的类型执行相应的操作:
- 如果字符是数字,则更新 cur_num。
- 如果字符是左括号 [,则将当前的字符串 cur_str 和数字 cur_num 入栈,并重置它们。
- 如果字符是右括号 ],则从栈中弹出之前保存的字符串和数字,并将当前字符串乘以该数字后与之前的字符串相加。
- 如果字符是字母,则将其添加到当前字符串 cur_str 中。
class Solution:
def decodeString(self, s: str) -> str:
# split,
stack = []
cur_num = 0
cur_str = ""
for ch in s:
if ch.isdigit():
cur_num= cur_num*10+int(ch)
elif ch == '[':
stack.append([cur_str, cur_num])
cur_str = ''
cur_num = 0
elif ch == ']':
pre_chr, num = stack.pop()
cur_str = pre_chr + cur_str*num
else:
cur_str+=ch
return cur_str