题意简述:给定一个解码规则k[encoded_string] -> encoded_string重复k次,以及一个根据此规则编码的字符串,求出解码后的字符串。
输入:编码的字符串s
输出:解码后的字符串
示例:字符串“3[a2[c]]”将被解码为“accaccacc”,3[a2[c]]=3[acc]=accaccacc
题解:
涉及到括号匹配和嵌套,因而采用DFS进行求解。
设置一个int记录当前处理的字符在字符串的下标cur,记在当前dfs函数中用来存放结果的字符串res。考虑当前处理的字符,只有4种可能:
- 当前字符是字母:直接在res末尾加入该字符,转到下一个字符。
- 当前字符是数字:设一个int记录应该重复的次数rep,因为重复的次数不一定只有一位数,所以需要把整个代表数的字符串找出来,cur一直增加直到遇到左方括号,然后将字符串计算转化为对应的数,例如“345”应该要算出345。
- 当前字符是左方括号:递归调用dfs函数,将返回的字符串重复rep次插入到res的末尾。
- 当前字符是右方括号:表示当前的dfs处理已完成,立刻返回res到上层的dfs函数。
当然如果已经到达字符串的末尾,也会返回res。
代码实现如下:
class Solution {
private:
int curind;
string mystr;
string dfs() {
string res;
while(curind < mystr.size()) {
if(isalpha(mystr[curind])) {
res.push_back(mystr[curind]);
curind++;
}
if(isdigit(mystr[curind])) {
int rep = 0;
while(isdigit(mystr[curind])) {
rep = rep * 10 + (mystr[curind] - '0');
curind++;
}
curind++;
string temp = dfs();
for(int i = 0;i < rep;i++) res += temp;
}
if(mystr[curind] == ']') {
curind++;
return res;
}
}
return res;
}
public:
string decodeString(string s) {
curind = 0;
mystr = s;
return dfs();
}
};