Given an encoded string, return its 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].
Example 1:
Input: s = “3[a]2[bc]”
Output: “aaabcbc”
Example 2:
Input: s = “3[a2[c]]”
Output: “accaccacc”
Example 3:
Input: s = “2[abc]3[cd]ef”
Output: “abcabccdcdcdef”
Example 4:
Input: s = “abc3[cd]xyz”
Output: “abccdcdcdxyz”
题目描述:就是将n[]这种特殊的String平摊开,自己知道肯定用StirngBuilder和Stack。这是我第一次用stack,所以还是思路不明确,借鉴了别人的想法,我觉得很好。
public String decodeString(String s) {
Stack<Node> stack = new Stack<>();
stack.push(new Node());
for (Character ch : s.toCharArray()){
if (Character.isDigit(ch)) {
int tmp = stack.peek().times;
//连续的数字前面的数字扩大十倍
tmp *= 10;
tmp += Character.digit(ch,10);
stack.peek().times = tmp;
continue;
}
if (ch == '['){
stack.push(new Node());
continue;
}
//[]中括号里边的字符串为一个node,当遇到]时
if (ch == ']'){
//这两句话保证了上一个Node中的String会重复多次并加到当前Node的StringBuilder
Node prve = stack.pop();
stack.peek().update(prve);
stack.peek().times = 0;
continue;
}
stack.peek().sb.append(ch);
}
return stack.pop().sb.toString();
}
private static class Node {
StringBuilder sb = new StringBuilder();
int times;
void update(Node prve) {
while (times-- > 0) {
sb.append(prve.sb);
}
}
}