用栈进行括号匹配
/**
* @program: exercise
* @description: 用栈进行括号匹配
* @author: yuuko
* @create: 2021-12-12 15:42
**/
import java.util.Scanner;
import java.util.Stack;
public class KuoHao {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String s=input.next();
System.out.println(solution(s));
}
public static boolean solution(String s){
Stack<Character> stack1=new Stack<>();
char currentCorrectChar;
for(int i=0;i<s.length();i++) {
switch (s.charAt(i)) {
case '(':
stack1.push(')');
break;
case '[':
stack1.push(']');
break;
case '{':
stack1.push('}');
break;
default:
if(stack1.isEmpty())
return false;
else
currentCorrectChar = stack1.pop();
if (currentCorrectChar != s.charAt(i))
return false;
}
}
if(!stack1.isEmpty())
return false;
return true;
}
}
自定义栈进行括号匹配
/**
* @program: exercise
* @description: 自己定义的栈
* @author: yuuko
* @create: 2021-12-12 15:49
**/
public class myCharStack {
private myCharStack header;
private myCharStack next=null;
private char content;
myCharStack(){
this.header=this;
}
myCharStack(char content){
this.content=content;
}
public void push(char content){
myCharStack stack1=new myCharStack(content);
stack1.next=this.header.next;
this.header.next=stack1;
}
public char pop(){
if(this.header.next==null){
System.out.println("EmptyStackException here");
return 'X';
}
char popContent=this.header.next.content;
this.header.next=this.header.next.next;
return popContent;
}
public boolean isEmpty(){
return this.header.next == null;
}
}
/**
* @program: exercise
* @description:
* @author: kkx
* @create: 2021-12-12 15:57
**/
import java.util.Scanner;
public class myKuoHao {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String s=input.next();
System.out.println(solution(s));
}
public static boolean solution(String s){
myCharStack stack1=new myCharStack();
char currentCorrectChar;
for(int i=0;i<s.length();i++) {
switch (s.charAt(i)) {
case '(':
stack1.push(')');
break;
case '[':
stack1.push(']');
break;
case '{':
stack1.push('}');
break;
default:
currentCorrectChar = stack1.pop();
if (currentCorrectChar != s.charAt(i))
return false;
}
}
if(!stack1.isEmpty())
return false;
return true;
}
}
评论 (0)