Problem
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.
For example, there won't be input like 3a or 2[4].
Example
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
Algorithm
整理一下题意:给定一个编码过的字符串,要求返回对应的解码字符串。编码规则是,k[s]表示[]中的字符串s要重复k次。假设k是正整数;输入有效,没有多余空格且方括号对应正确;方括号中只有字母,没有数字。
本题的难点在于需要考虑嵌套的情况。整理一下,对于每个字符串,如果是无嵌套的情况,遇到数字则以数字为倍数保存后续方括号中的内容。如果含嵌套,则嵌套的内容视为子问题递归求解。对于不涉及方括号的情况,此时给定字符串中出现普通的字符,这部分字符直接附加到结果串中。
在不同层次的递归中,指向的位置是顺序的,故维护一个共同的位置索引,可以通过引用参数“&”来实现。
特别注意[]前的数字不一定是个位数,需要进行简单的计算。
//DFS
class Solution {
public:
string decodeString(string s) {
if(s.size()==0) return "";
int i=0;
return dfs(s,i);
}
string dfs(string s, int& i){
string ans;
int count=0;
while(i<s.size()){
if(s[i]>='0'&&s[i]<='9'){
count=(count*10+s[i]-'0');
i++;
}
else if(s[i]=='['){
i++;
string t=dfs(s,i);
for(int j=0;j<count;j++) ans+=t;
count=0;
}
else if(s[i]==']'){
i++;
return ans;
}
else{
ans+=s[i];
i++;
}
}
return ans;
}
};