LeetCode 刷题笔记 2. 有效的括号(Valid Parentheses)

tag: 栈(stack)

题目描述

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

python版本1:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        for ch in s:
            if ch == '{' or ch == '[' or ch == '(':
                stack.append(ch)
            else:
                if not stack:
                    return False
                if ch == ']' and stack[-1] != '[' or ch == ')' and stack[-1] != '(' or ch == '}' and stack[-1] != '{':
                    return False
                stack.pop()
        
        return not stack

python版本2:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        
        mapping = {")": "(", "}": "{", "]": "["};
        
        for char in s:
            if char in mapping:
                top_element = stack.pop() if stack else '#'
                
                if mapping[char] != top_element:
                    return False
            
            else:
                stack.append(char)
                
        return not stack

java版本:

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 (int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            
            if (this.mappings.containsKey(c)){
                char topElement = stack.empty() ? '#' :stack.pop();
                
                if(topElement != this.mappings.get(c)){
                    return false;
                }
                
            }else {
                stack.push(c);
            }
        }
        
        return stack.isEmpty();
    }
}

复杂度分析

  • 时间复杂度:O(n)O(n),因为我们一次只遍历给定的字符串中的一个字符并在栈上进行 O(1)O(1) 的推入和弹出操作。
  • 空间复杂度:O(n)O(n),当我们将所有的开括号都推到栈上时以及在最糟糕的情况下,我们最终要把所有括号推到栈上。例如 ((((((((((。
posted @ 2019-03-05 15:27  今羽  阅读(269)  评论(0编辑  收藏  举报