思路:
1、将字符串的每个字符进行遍历
2、如果发现是左括号,那么将该字符压入到栈中
3、如果是右括号,先去存储好的栈顶找到相应的值
4、若栈为空返回false,若匹配,pop该左括号,若不匹配也返回false
5、最后看存储栈中的做括号是否都匹配上了,也就是栈最后为空,返回true,否则返回falsepublic class T3 {
public static void main(String[] args) {
System.out.println(isMatch("asdasdadasdasdsa"));
System.out.println(isMatch("{ada(ada)asdas}"));
System.out.println(isMatch("{asdasd(asdasdasd}asda)"));
}
static boolean isMatch(String s) {
if (null == s) {
return false;
}
//定义左右括号的对应关系
Map bracket = new HashMap<>();
bracket.put('(', ')');
bracket.put('{', '}');
bracket.put('[', ']');
Stack stack = new Stack<>();
char[] chars = s.toCharArray();
for (Character temp : chars) {
if (bracket.containsKey(temp)) {
stack.push(temp);
} else if (bracket.containsValue(temp)) {
if (stack.isEmpty()) {
return false;
}
if (bracket.get(stack.peek()).equals(temp)) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
}