Repository navigation
Expand file tree
/
Copy pathDecodeString.java
More file actions
80 lines (60 loc) · 2.01 KB
/
Copy pathDecodeString.java
File metadata and controls
80 lines (60 loc) · 2.01 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.abn.dsalgos.datastructure.stack;
/*
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.
Note that k is guaranteed to be a positive integer.
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Input: s = "3[a2[c]]"
Output: "accaccacc"
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class DecodeString {
public String decodeString(String s) {
Map<Integer, Integer> bracketMap = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for(int i = 0; i<s.length(); i++) {
char ch = s.charAt(i);
if(ch == '[') {
stack.push(i);
} else if(ch == ']') {
bracketMap.put(stack.pop(), i);
}
}
String str = decodeHelper(s, bracketMap, 0, s.length() - 1);
return str;
}
private String decodeHelper(String s, Map<Integer, Integer> map, int start, int end) {
if(start == s.length()) {
return "";
}
StringBuilder sb = new StringBuilder();
int num = 0;
for(int i = start; i <= end; i ++) {
char ch = s.charAt(i);
if(Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
} else if(ch == '['){
int endIndex = map.get(i);
String str = decodeHelper(s, map, i + 1, endIndex - 1);
for(int j = 0; j < num - 1; j++) {
sb.append(str);
}
num = 0;
} else if(ch == ']') {
continue;
}
else {
sb.append(ch);
}
}
return sb.toString();
}
public static void main(String[] args) {
DecodeString decode = new DecodeString();
System.out.println(decode.decodeString("3[a]2[bc]"));
System.out.println(decode.decodeString("10[abcd]"));
}
}