|
1 | 1 | class Solution {
|
2 | 2 | public String decodeString(String s) {
|
3 |
| - Stack<Integer> countStack = new Stack<>(); |
4 |
| - Stack<String> wordStack = new Stack<>(); |
5 |
| - StringBuilder sb = new StringBuilder(); |
6 |
| - int idx = 0; |
7 |
| - while (idx < s.length()) { |
8 |
| - if (Character.isDigit(s.charAt(idx))) { |
9 |
| - int count = 0; |
10 |
| - while (idx < s.length() && Character.isDigit(s.charAt(idx))) { |
11 |
| - count = count * 10 + Character.getNumericValue(s.charAt(idx++)); |
| 3 | + Stack<Character> stack = new Stack<>(); |
| 4 | + for (char c : s.toCharArray()) { |
| 5 | + if (c == ']') { |
| 6 | + StringBuilder sb = new StringBuilder(); |
| 7 | + while (!stack.isEmpty() && stack.peek() != '[') { |
| 8 | + sb.append(stack.pop()); |
12 | 9 | }
|
13 |
| - countStack.push(count); |
14 |
| - } else if (Character.isLetter(s.charAt(idx))) { |
15 |
| - sb.append(s.charAt(idx++)); |
16 |
| - } else if (s.charAt(idx) == '[') { |
17 |
| - wordStack.push(sb.toString()); |
18 |
| - sb.setLength(0); |
19 |
| - idx++; |
20 |
| - } else { |
21 |
| - StringBuilder temp = new StringBuilder(wordStack.pop()); |
22 |
| - String currentString = sb.toString(); |
| 10 | + stack.pop(); |
| 11 | + String temp = sb.toString(); |
23 | 12 | sb.setLength(0);
|
24 |
| - int count = countStack.pop(); |
| 13 | + while (!stack.isEmpty() && Character.isDigit(stack.peek())) { |
| 14 | + sb.append(stack.pop()); |
| 15 | + } |
| 16 | + int count = Integer.parseInt(sb.reverse().toString()); |
25 | 17 | while (count-- > 0) {
|
26 |
| - temp.append(currentString); |
| 18 | + for (int i = temp.length() - 1; i >= 0; i--) { |
| 19 | + stack.push(temp.charAt(i)); |
| 20 | + } |
27 | 21 | }
|
28 |
| - sb.append(temp); |
29 |
| - idx++; |
| 22 | + } else { |
| 23 | + stack.push(c); |
30 | 24 | }
|
31 | 25 | }
|
32 |
| - return sb.toString(); |
| 26 | + StringBuilder sb = new StringBuilder(); |
| 27 | + while (!stack.isEmpty()) { |
| 28 | + sb.append(stack.pop()); |
| 29 | + } |
| 30 | + return sb.reverse().toString(); |
33 | 31 | }
|
34 | 32 | }
|
0 commit comments