394. Decode String¶
Difficulty: Medium
LeetCode Problem View on GitHub
394. Decode String
Medium
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.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]" Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]" Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef"
Constraints:
1 <= s.length <= 30sconsists of lowercase English letters, digits, and square brackets'[]'.sis guaranteed to be a valid input.- All the integers in
sare in the range[1, 300].
Solution¶
class Solution {
public String decodeString(String s) {
int n = s.length();
Stack<Integer> dig = new Stack<>();
Stack<Character> ch = new Stack<>();
int num = 0;
for (int i = 0; i < n; i++) {
char current = s.charAt(i);
if (Character.isDigit(current)) num = num * 10 + (int)(current - '0');
else {
if (num > 0) dig.add(num);
num = 0;
if (current == ']') {
StringBuilder current_string = new StringBuilder();
while (ch.size() > 0 && ch.peek() != '[') {
current_string.append(ch.peek());
ch.pop();
}
ch.pop();
String new_string = current_string.reverse().toString();
StringBuilder to_add = new StringBuilder("");
for (int j = 0; j < dig.peek(); j++) to_add.append(new_string);
dig.pop();
for (int j = 0; j < to_add.length(); j++) ch.add(to_add.charAt(j));
}
else ch.add(current);
}
}
StringBuilder res = new StringBuilder();
while (ch.size() > 0) res.append(ch.pop());
return res.reverse().toString();
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here