有效的括号
有效的括号
题目
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。示例 1:
输入: "()"
输出: true
示例 2:输入: "()[]{}"
输出: true
示例 3:输入: "(]"
输出: false
示例 4:输入: "([)]"
输出: false
示例 5:输入: "{[]}"
输出: true来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决方法
思路
- 栈先入后出特点正好能满足题目要求,有左括号就入栈,右括号就取栈顶左括号,判断是否有效。
 - 通过Map键值对建立左右括号对应关系。
 
算法
- 如果是左括号,就入栈 push。
 - 以外就取出栈顶的左括号 pop,通过取出的左括号为key在Map中找到对应的value,与当前括号比较。
 

class Solution{
    private HashMap<Character,Character> mappings;
    
    public Solution(){
        this.mappings = new HashMap<Character,Character>();
        this.mappings.put('(', ')');
        this.mappings.put('[', ']');
        this.mappings.put('{', '}');
    }
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (Character c : s.toCharArray()) {
            if (mappings.containsKey(c)) {
                stack.push(c);
            } else {
                char top = stack.empty() ? '#' : stack.pop();
                if (c != mappings.get(top)) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
本文来自博客园,作者:Mazy_699,转载请注明原文链接:https://www.cnblogs.com/mazy-699/p/16260046.html

                
            
        
浙公网安备 33010602011771号