题目
394-字符串解码
回溯/递归法
该方法利用递归的方式,遍历所有路线。当一种路线不满足要求,便返回。
解答-394题
1. 题目
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = “3[a]2[bc]”, 返回 “aaabcbc”.
s = “3[a2[c]]”, 返回 “accaccacc”.
s = “2[abc]3[cd]ef”, 返回 “abcabccdcdcdef”.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 思路
首先观察,可以利用回溯方法,但要注意两个退出条件和两种写入。
写入方式1:如果没有数字,只有字母,正常写入;
方式2:如果有数字n,则数字后面的【】中会重复n次
退出条件1:如果是在主函数中调用该函数,则退出条件应该是字符串到达末尾
条件2:如果是在数字后,重复n次用该函数,则退出条件应该是到达‘【’对应的‘】’
3. 代码
void BackTrace(char *out, int* deep, char* s, int pos, int* posOut)
{
int num, i, col;
if (s[pos] == '[') {
pos++;
}
while (s[pos] != '\0') {
num = 0;
if (s[pos] == ']') {
*posOut = pos + 1;
return;
}
while ((s[pos] <= 'z' && s[pos] >= 'a') || (s[pos] <= 'Z' && s[pos] >= 'A')) {
out[*deep] = s[pos];
(*deep)++;
pos++;
}
if (s[pos] <= '9' && s[pos] >= '0') {
while (s[pos] != '[') {
num *= 10;
num += (s[pos] - '0');
pos++;
}
for (i = 0; i < num; i++) {
BackTrace(out, deep, s, pos, posOut);
}
pos = *posOut;
}
}
*posOut = pos;
}
char * decodeString(char * s){
char* out = (char*)malloc(5000 * sizeof(char));
int deep, posOut;
deep = 0;
BackTrace(out, &deep, s, 0, &posOut);
out[deep] = '\0';
return out;
}