火大教育web3.0应用工程师培养计划
计算匹配的括号
public class ParenthesisMatching {
// [] => valid
// {[]} => valid
// [(]) => invalid
public static void main(String[] args) {
System.out.println(isValid("[]"));
System.out.println(isValid("{[]}"));
System.out.println(isValid("{[]}()"));
System.out.println(isValid("{[]}([)]"));
}
public static boolean isValid(String string) {
Map<Character, Character> bracketMap = new HashMap<>();
bracketMap.put('[', ']');
bracketMap.put('(', ')');
bracketMap.put('{', '}');
if (string == null || string.isEmpty()) {
return true;
}
Deque<Character> stack = new ArrayDeque<>();
char[] chars = string.toCharArray();
for (char ch : chars) {
if ("[{(".indexOf(ch) >= 0) {
stack.push(ch);
continue;
}
Character head = stack.peek();
if ("]})".indexOf(ch) >= 0) {
if (head != null && ch == bracketMap.get(head)) {
stack.pop();
continue;
} else {
return false;
}
}
throw new IllegalArgumentException("参数非法:" + string);
}
return stack.isEmpty();
}}