0
点赞
收藏
分享

微信扫一扫

leetcode 20. Valid Parentheses(有效括号)

Villagers 2022-03-13 阅读 52

Given a string s containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

Example 1:

Input: s = “()”
Output: true
Example 2:

Input: s = “()[]{}”
Output: true

括号是否匹配的问题。而且字符串s中只有括号,没有其他字符。

思路:
典型的stack问题。
遇到"(", “[”, "{“压栈,遇到“)” “]”, "}"就看栈顶是不是与之对应的括号,出栈,如果这时栈为空或者不匹配,返回false。
最后如果栈为空,说明完全匹配,返回true。

    public boolean isValid(String s) {
        if(s.length() < 2) return false;
        HashMap<Character, Character> map = new HashMap<>();
        Stack<Character> stack = new Stack<>();
        
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        
        for(int i = 0; i < s.length(); i ++) {
            char ch = s.charAt(i);
            if(map.containsKey(ch)) {
                stack.push(ch);
            } else {
                if(stack.isEmpty() || 
                   ch != map.get(stack.pop())) return false;
            }
        }
        
        return (stack.isEmpty());
    }

也可以不用map,直接比较各括号,但是会慢一点

    public boolean isValid(String s) {
        if(s.length() < 2) return false;
        Stack<Character> stack = new Stack<>();
        
        for(int i = 0; i < s.length(); i ++) {
            char ch = s.charAt(i);
            if(ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if(stack.isEmpty()) return false;
                char pair = stack.pop();
                if((ch == ')' && pair != '(') || 
                   (ch == ']' && pair != '[') ||
                    (ch == '}' && pair != '{')) return false;
            }
        }
        
        return (stack.isEmpty());
    }
举报

相关推荐

0 条评论