https://leetcode.com/problems/decode-string/
这一题给的条件太友善了,主要是没有3a或者2[4]这样的输出,这样逻辑判断就很简单了。因为中括号允许内部嵌套,这样的话最好的方式还是自下而上的dfs递归会比较方便。用一个全局的遍历计数器,然后基本就是分几个case
1. 遇到0 ~ 9,就算进一个counter里表示对下一层递归返回的字符串重复多少次
2. 遇到[, 就表示进入下一个递归层。然后对下一递归层返回的字符串,重复添加counter次数到结果
3. 遇到],就表示这个递归层结束了,返回字符串
4. 遇到其他字符,直接添加到结果
5. 全局的遍历计数器走完也返回字符串,就表示已经跑完了
根据上述描述得到代码如下:
public String decodeString(String s) {
int[] pos = new int[1];
return decodeString(s, pos);
}
public String decodeString(String s, int[] curPos) {
StringBuilder builder = new StringBuilder();
int curTimes = 0;
for (; curPos[0] < s.length(); curPos[0]++) {
char ch = s.charAt(curPos[0]);
if (ch >= '0' && ch <= '9') {
curTimes = curTimes * 10 + (ch - '0');
} else if (ch == '[') {
curPos[0]++;
String nextRecur = decodeString(s, curPos);
for (int i = 0; i < curTimes; i++) {
builder.append(nextRecur);
}
curTimes = 0;
} else if (ch == ']') {
return builder.toString();
} else {
builder.append(ch);
}
}
return builder.toString();
}