火大教育web3.0應(yīng)用工程師培養(yǎng)計(jì)劃
計(jì)算匹配的括號(hào)
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("參數(shù)非法:" + string);
? ? ? ?}
? ? ? ?return stack.isEmpty();
? ?}}