第一种:
/**
* 判断括号匹配是否正确
*
* ab[c(sa)s]d: true
* ab[c(sa])sd: false
*
* @param str
* @return
*/
public static boolean check(String str) {
//利用map存储对应的括号
HashMap<Character,Character> map = new HashMap<>();
map.put('{', '}');
map.put('[', ']');
map.put('(', ')');
//用栈存储字符串中出现的括号
Stack<Character> stack = new Stack<>();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i); //取出字符串中的每个字符
//判断字符 c 是不是需要匹配的括号
if(map.containsKey(c) || map.containsValue(c)) {
//如果栈不空,取出栈顶元素与括号c比较
if(!stack.isEmpty()) {
char cc = stack.pop();
//从map中取出左括号对应的右括号,与括号c比较,如果不相等则不匹配,需要压入栈
//如果匹配则进行下一个字符的判断
if(map.get(cc) != null && map.get(cc) != c) {
stack.push(cc);
stack.push(c);
}
//栈空则压入栈
}else {
stack.push(c);
}
}
}
//遍历完字符串,如果此时栈是空的,则说明括号匹配全部正确
return stack.empty();
}
第二种:
public class Main {
private String left;
private String right;
public Main() {
left = "{[(";
right = "}])";
}
public static void main(String[] args){
Main m = new Main();
System.out.println(m.check("ab[c()(sas)]d"));
}
private boolean check(String str){
if(str == null) {
throw new NullPointerException();
}
//创建栈存储出现的括号
Stack<Character> s = new Stack<>();
for(int i = 0; i < str.length(); i++) {
//取出每个字符
char ch = str.charAt(i);
//判断该字符是不是括号
//如果字符在串中存在,则下标大于等于0,不存在-1
if(left.indexOf(ch) >= 0 || right.indexOf(ch) >= 0) {
//是左括号直接入栈
if(left.indexOf(ch) >= 0) {
s.push(ch);
}else if(right.indexOf(ch) >= 0) {
//是右括号则判断栈是否为空,空栈则括号不匹配直接返回false
if(s.empty()) {
return false;
}else {
//栈不空判断栈顶括号在左串中的位置和字符在右串中的位置是否相同,相同则匹配,弹出栈顶元素
if(left.indexOf(s.peek()) == right.indexOf(ch)) {
s.pop();
}else {
//串中位置不同则不是匹配的括号,字符入栈
s.push(ch);
}
}
}
}
}
//栈空则匹配,栈不空则匹配失败
return s.empty();
}
}