Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2ae7e08

Browse files
Update solution for Decode String
1 parent 71eda3c commit 2ae7e08

File tree

1 file changed

+24
-21
lines changed

1 file changed

+24
-21
lines changed

‎src/solutions/DecodeString.java

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,31 +7,34 @@ class DecodeString {
77
// Stack
88
// O(n) time, O(n) space
99
public String decodeString(String s) {
10-
Stack<Integer> repeatCounts = new Stack<>();
11-
Stack<String> storedStrings = new Stack<>();
12-
storedStrings.push("");
13-
14-
int i = 0;
15-
while (i < s.length()) {
16-
char ch = s.charAt(i);
17-
if (Character.isDigit(ch)) {
18-
int start = i;
19-
while (Character.isDigit(s.charAt(i + 1))) {
20-
i++;
10+
int num = 0;
11+
Stack<String> stack = new Stack<>();
12+
for (int i = 0; i < s.length(); i++) {
13+
char c = s.charAt(i);
14+
if (Character.isDigit(c)) {
15+
num = num * 10 + (c - '0');
16+
} else if (c == '[') {
17+
stack.push(String.valueOf(num));
18+
stack.push("[");
19+
num = 0;
20+
} else if (c == ']') {
21+
String substring = "";
22+
while (!stack.empty() && !"[".equals(stack.peek())) {
23+
substring = stack.pop() + substring;
2124
}
22-
repeatCounts.push(Integer.parseInt(s.substring(start, i + 1)));
23-
} else if (ch == '[') {
24-
storedStrings.push("");
25-
} else if (ch == ']') {
26-
String repeatStr = storedStrings.pop();
27-
int repeatCount = repeatCounts.pop();
28-
storedStrings.push(storedStrings.pop() + repeatStr.repeat(repeatCount));
25+
stack.pop(); // pop '['
26+
int repeatCount = Integer.parseInt(stack.pop());
27+
String repeatedSubstring = substring.repeat(repeatCount);
28+
stack.add(repeatedSubstring);
2929
} else {
30-
storedStrings.push(storedStrings.pop() + ch);
30+
stack.push(String.valueOf(c));
3131
}
32-
i++;
3332
}
34-
return storedStrings.pop();
33+
String result = "";
34+
while (!stack.empty()) {
35+
result = stack.pop() + result;
36+
}
37+
return result;
3538
}
3639

3740
// Test

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /