classSolution{publicbooleanisValid(String s){if(s.length()==0)returntrue;if((s.length()&1)==1)returnfalse;
Stack<Character> stack =newStack<>();for(int i =0; i < s.length(); i++){switch(s.charAt(i)){case'(':case'[':case'{':
stack.push(s.charAt(i));continue;case')':if(stack.isEmpty()|| stack.pop()!='(')returnfalse;continue;case']':if(stack.isEmpty()|| stack.pop()!='[')returnfalse;continue;case'}':if(stack.isEmpty()|| stack.pop()!='{')returnfalse;continue;}}return stack.isEmpty();}}
用队列实现栈
classMyStack{
Queue<Integer> queue;/** Initialize your data structure here. */publicMyStack(){
queue =newLinkedList<>();}/** Push element x onto stack. */publicvoidpush(int x){
queue.offer(x);}/** Removes the element on top of the stack and returns that element. */publicintpop(){int size = queue.size();for(int i =0; i < size -1; i++){
queue.offer(queue.poll());}return queue.poll();}/** Get the top element. */publicinttop(){int size = queue.size();for(int i =0; i < size -1; i++){
queue.offer(queue.poll());}int result = queue.poll();
queue.offer(result);return result;}/** Returns whether the stack is empty. */publicbooleanempty(){return queue.isEmpty();}}