Version #1 Stack
很多java语法方面的问题可以学到
public class Solution {
/**
* @param s an expression includes numbers, letters and brackets
* @return a string
*/
public String expressionExpand(String s) {
// Write your code here
Stack<Object> stack = new Stack<>();
Stack<Character> buffer = new Stack<>();
Integer num = 0;
char curr;
for (int index = 0; index < s.length(); index++) {
curr = s.charAt(index);
if (Character.isDigit(curr)) {
num = num * 10 + curr - '0';
} else if (curr == '[') {
stack.push(num);
num = 0;
} else if (curr == ']') {
String str = popStack(stack);
Integer count = stack.isEmpty() ? 0 : (Integer)stack.pop();
//System.out.println(count);
for (int i = 0; i < count; i++) {
stack.push(str);
}
} else {
stack.push(String.valueOf(curr));
}
}
return popStack(stack);
}
private String popStack(Stack<Object> stack) {
Stack<String> buffer = new Stack<>();
while (!stack.isEmpty() && (stack.peek() instanceof String)) {
buffer.push((String)stack.pop());
}
StringBuilder sb = new StringBuilder();
while (!buffer.isEmpty()) {
sb.append(buffer.pop());
}
//System.out.println(sb.toString());
return sb.toString();
}
}
No comments:
Post a Comment