232.用栈实现队列
Collection------List------Vector类------Stack类
java
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn=new Stack();
stackOut=new Stack();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
notempty();
return stackOut.pop();
}
public int peek() {
notempty();
return stackOut.peek();
}
public boolean empty() {
if(stackIn.isEmpty()&&stackOut.isEmpty())
return true;
else
return false;
}
public void notempty(){
if(!stackOut.isEmpty())
return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225. 用队列实现栈
Collection------Queue------LinkedList类
java
class MyStack {
Queue<Integer> myStack;
public MyStack() {
myStack=new LinkedList();
}
public void push(int x) {
myStack.offer(x);
int size=myStack.size();
for(int i=0;i<size-1;i++){
myStack.offer(myStack.poll());
}
}
public int pop() {
return myStack.poll();
}
public int top() {
return myStack.peek();
}
public boolean empty() {
return myStack.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
20. 有效的括号
Collection------Deque------LinkedList类
java
class Solution {
public boolean isValid(String s) {
Deque<Character> mystack=new LinkedList();
char a;
char[] ch=s.toCharArray();
for(int i=0;i<ch.length;i++){
a=ch[i];
if(a=='('){
mystack.push(')');
}
else if(a=='{'){
mystack.push('}');
}
else if(a=='['){
mystack.push(']');
}
else if(mystack.isEmpty()||mystack.peek()!=a){
return false;
}
else{
mystack.pop();
}
}
return mystack.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
StringBuilder(StringBuffer)
java
class Solution {
public String removeDuplicates(String s) {
StringBuffer sb=new StringBuffer();
int index=-1;
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(sb.length()==0||sb.charAt(index)!=ch){
index++;
sb.append(ch);
}else{
sb.deleteCharAt(index);
index--;
}
}
return sb.toString();
}
}