描述:
给定一个字符串,其中的字符只包含三种括号:花括号{ }、中括号[ ]、圆括号( ),即它仅由 “( ) [ ] { }” 这六个字符组成。设计算法,判断该字符串是否有效,即字符串中括号是否匹配。括号匹配要求括号必须以正确的顺序配对,如 “{ [ ] ( ) }” 或 “[ ( { } [ ] ) ]” 等为正确的格式,而 “[ ( ] )” 或 “{ [ ( ) }” 或 “( { } ] )” 均为不正确的格式。
思路:
数据结构选用栈,读到左括号时入栈,读到右括号时判断是否匹配,匹配则左括号出栈,最后判断栈为空说明匹配,不为空不匹配。
代码:
public class isMatch {
public static void main(String[] args) {
String string ="([a+b]-(rr{}))";
boolean res = match(string);
System.out.println(res);
}
public static boolean match(String str) {
Map map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack stack =new Stack<>();
for(int i=0;i