-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecodeString.java
62 lines (53 loc) · 1.28 KB
/
DecodeString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package string;
import java.util.*;
/**
* @author Shogo Akiyama
* Solved on 12/11/2019
*
* 394. Decode String
* https://leetcode.com/problems/decode-string/
* Difficulty: Medium
*
* Approach: Iteration
* Runtime: 1 ms, faster than 68.70% of Java online submissions for Decode String.
* Memory Usage: 35.9 MB, less than 36.36% of Java online submissions for Decode String.
*
* Time Complexity: O(n)
* Space Complexity: O(n)
* Where n is the length of a string
*
* @see StringTest#testDecodeString()
*/
public class DecodeString {
public String decodeString(String s) {
String result = "";
Stack<String[]> stack = new Stack<String[]>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
int index = i;
while (Character.isDigit(s.charAt(++index)))
;
String[] newString = new String[] { s.substring(i, index), "" };
stack.push(newString);
i = index;
} else {
String curr = "";
if (c == ']') {
String[] data = stack.pop();
for (int j = 0; j < Integer.parseInt(data[0]); j++) {
curr += data[1];
}
} else {
curr = s.charAt(i) + "";
}
if (stack.isEmpty()) {
result += curr;
} else {
stack.peek()[1] += curr;
}
}
}
return result;
}
}