Skip to content

Commit b1c3edd

Browse files
authored
Update Decode String.java
1 parent 6a4ed92 commit b1c3edd

File tree

1 file changed

+22
-24
lines changed

1 file changed

+22
-24
lines changed

Medium/Decode String.java

+22-24
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,32 @@
11
class Solution {
22
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());
129
}
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();
2312
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());
2517
while (count-- > 0) {
26-
temp.append(currentString);
18+
for (int i = temp.length() - 1; i >= 0; i--) {
19+
stack.push(temp.charAt(i));
20+
}
2721
}
28-
sb.append(temp);
29-
idx++;
22+
} else {
23+
stack.push(c);
3024
}
3125
}
32-
return sb.toString();
26+
StringBuilder sb = new StringBuilder();
27+
while (!stack.isEmpty()) {
28+
sb.append(stack.pop());
29+
}
30+
return sb.reverse().toString();
3331
}
3432
}

0 commit comments

Comments
 (0)