| 1 | class Solution { |
| 2 | public String decodeString(String s) { |
| 3 | StringBuilder res = new StringBuilder(); |
| 4 | int multi = 0; |
| 5 | |
| 6 | Stack<Integer> stack_multi = new Stack(); |
| 7 | Stack<String> stack_res = new Stack(); |
| 8 | |
| 9 | for (int i = 0; i < s.length(); i++) { |
| 10 | char c = s.charAt(i); |
| 11 | if ('[' == c){ |
| 12 | stack_multi.push(multi); |
| 13 | stack_res.push(res.toString()); |
| 14 | multi = 0; |
| 15 | res = new StringBuilder(); |
| 16 | } |
| 17 | else if (']' == c) { |
| 18 | StringBuilder tmp = new StringBuilder(); |
| 19 | int cur_multi = stack_multi.pop(); |
| 20 | for (int j = 0; j < cur_multi; j++){ |
| 21 | tmp.append(res); |
| 22 | } |
| 23 | res = new StringBuilder(stack_res.pop() + tmp); |
| 24 | } |
| 25 | else if(c >= '0' && c <= '9'){ |
| 26 | multi = multi * 10 + (c - '0'); |
| 27 | } |
| 28 | else{ |
| 29 | res.append(c); |
| 30 | } |
| 31 | } |
| 32 | return res.toString(); |
| 33 | } |
| 34 | } |