题目描述:括号匹配问题
(()))不匹配
[(())]匹配
[((((])))不匹配
)(不匹配
方法:采用栈
的数据结构进行括号的存储和匹配
栈
的特点:前进后出
程序代码:
import java.util.Scanner;
import java.util.Stack;
public class KuohaoMatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String bds = sc.next();
Stack<Character> s = new Stack<Character>();
if(bds.equals("#")) break;
char[] c = bds.toCharArray();
int i=0;
for(;i<c.length;i++) {
if(c[i]=='('||c[i]=='[') {
s.push(c[i]);//左括号入栈
} else if(c[i]==']') {
if(s.isEmpty()||s.pop()!='[') break;
} else if(c[i]==')') {
if(s.isEmpty()||s.pop()!='(') break;
}
}
if(s.size()==0 && i==c.length) {
System.out.println("匹配");
} else {
System.out.println("不匹配");
}
}
}
}