232 用栈实现队列
class MyQueue {
private static Stack<Integer> inStack;
private static Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<Integer>();
outStack = new Stack<Integer>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (outStack.isEmpty()){
inToOut();
}
return outStack.pop();
}
public int peek() {
if (outStack.isEmpty()){
inToOut();
}
return outStack.peek();
}
public boolean empty() {
return outStack.isEmpty() && inStack.isEmpty();
}
public void inToOut(){
while (!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
字符串解码
public String decodeString(String s) {
String res = "";
Stack<Integer> countStack = new Stack<>();
Stack<String> resStack = new Stack<>();
int index = 0;
while (index < s.length()){
char curr = s.charAt(index);
if (Character.isDigit(curr)){
StringBuffer ret = new StringBuffer();
while (Character.isDigit(s.charAt(index))){
ret.append(s.charAt(index++));
}
countStack.push(Integer.parseInt(ret.toString()));
} else if (curr == '[') {
resStack.push(res);
res = "";
index++;
} else if (curr == ']') {
StringBuffer temp = new StringBuffer(resStack.pop());
int repeatTimes = countStack.pop();
for (int i = 0; i < repeatTimes; i++) {
temp.append(res);
}
res = temp.toString();
index++;
}
else {
res += s.charAt(index++);
}
}
return res;
}