Loading

括号匹配(牛客网高频面试)

括号匹配

题目描述

给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。

代码实现:

首先设置一个mp,用于记录 三种括号对。
左括号:当前符号入栈:
右括号:栈顶元素是否和我当前符号的括号成对,成对则匹配成功:
=> 不成对 或者栈为空 ,则匹配失败。

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    public boolean isValid (String s) {
        // write code here
        Deque<Character> stack = new ArrayDeque<> ();
        HashMap<Character,Character> mp = new HashMap<> ();
        // 右括号 需要pop因此,需要查询对应的左括号;
        mp.put('}','{');
        mp.put(')','(');
        mp.put(']','[');
        
        for(int i = 0; i < s.length(); i++){
            // 左括号,入栈;
            if(!mp.containsKey(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                // 成功比匹配条件: 非空栈,并且栈顶左括号  与 当前 右括号匹配; => 此时pop;
                if(!stack.isEmpty() && stack.peek() == mp.get(s.charAt(i)))
                   stack.pop();
                // 其他情况:比方说,栈是空的,或者不匹配 都只能返回false;
                else
                    return false;
            }
        }
        return stack.isEmpty();
    }
}
posted @ 2020-11-27 12:15  Sidewinder  阅读(227)  评论(0编辑  收藏  举报