Decode String
Example
Note
Code
public class Solution {
// https://leetcode.com/problems/decode-string/description/
/**
* @param s: an expression includes numbers, letters and brackets
* @return: a string
*/
public String expressionExpand(String s) {
// write your code here
if (s == null) {
return null;
}
if (s.equals("")) {
return "";
}
Stack<StringBuilder> ss = new Stack<>();
Stack<Integer> sc = new Stack<>();
StringBuilder curr = new StringBuilder();
int count = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
count = count * 10 + (c - '0');
} else if (c == '[') {
sc.push(count);
count = 0;
ss.push(curr);
curr = new StringBuilder();
} else if (c == ']') {
int num = sc.pop();
StringBuilder temp = new StringBuilder();
temp.append(ss.pop());
while (num-- > 0) {
temp.append(curr);
}
curr = temp;
} else {
curr.append(c);
}
}
return curr.toString();
}
}Last updated