import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class java3_28_1 {
//括号匹配问题
public boolean isValid(String s) {
//创建一个栈将向右的括号加入到栈中
Stack<Character> stack=new Stack<>();
//在循环遍历如果是右括号就加入到栈中
//也可以创建一个Map
Map<Character,Character> map=new HashMap<>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
for(int i=0;i<s.length();i++) {
char A = s.charAt(i);
if (A == '(' || A == '{' || A == '[') {
stack.push(A);
continue;
}
if (stack.empty()) {
return false;
}
// char B=stack.pop();
// if(B=='('&&A=='('){
// continue;
// }if(B=='{'&&A=='}'){
// continue;
// }if(B=='['&&A==']'){
// continue;
// }
// return false;
// }
char B = stack.pop();
if (map.get(B) == A) {
continue;
}
return false;
}
if(!stack.empty()){
return false;
}
return true;
}
}
import java.util.Stack;
public class MinStack {
Stack<Integer> A=new Stack<>();
Stack<Integer> B=new Stack<>();
public void push(int x) {
A.push(x);
if(B.empty()){
B.push(x);
return ;
}
int min=B.peek();
if(x>min){
x=min;
}
B.push(x);
}
public Integer pop(){
if(A.isEmpty()){
return null;
}
B.pop();
return A.pop();
}
public Integer top() {
if(A.isEmpty()){
return null;
}
return A.peek();
}
public Integer getMin() {
if(A.empty()){
return null;
}
return B.peek();
}
}
import java.util.LinkedList;
import java.util.Queue;
public class MyStackBy2Queue {
Queue<Integer> A=new LinkedList<>();
Queue<Integer> B=new LinkedList<>();
//压栈
public void push(int x) {
A.offer(x);
}
//出栈
public Integer pop() {
if(empty()){
return null;
}
while(A.size()>1){
Integer num=A.poll();
B.offer(num);
}
int ret=A.poll();
swapAB();
return ret;
}
public void swapAB(){
Queue<Integer> temp=A;
A=B;
B=temp;
}
//获取栈顶元素
public Integer top() {
if(empty()){
return null;
}
while(A.size()>1){
Integer num=A.poll();
B.offer(num);
}
int ret=A.poll();
B.offer(ret);
swapAB();
return ret;
}
//判断栈是否为空
public boolean empty() {
return A.isEmpty()&&B.isEmpty();
}
}
public class QueueBy21Stack {
Stack<Integer> A=new Stack<>();
Stack<Integer> B=new Stack<>();
//压栈B栈石佛语为空,如果不为空,将B栈中的元素压入A栈中.
public void push(int v){
//判断
while(!B.empty()){
int temp=B.push(v);
A.push(temp);
}
A.push(v);
}
// 出栈
public Integer pop(){
if(A.empty()){
return null;
}
while(!A.empty()) {
int num=A.pop();
B.push(num);
}
return B.pop();
}
//获取栈顶元素
public Integer peek(){
if(A.empty()){
return null;
}
while(!A.empty()){
int num=A.pop();
B.push(num);
}
return B.pop();
}
//判断栈是否为空
public boolean isEmpty(){
return A.empty()&&B.empty();
}
}