zoukankan      html  css  js  c++  java
  • [LeetCode] 20. Valid Parentheses 合法括号

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

    An input string is valid if:

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

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

    Input: "()[]{}"
    Output: true
    

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true

    输入的字符串只含有'('')''{''}''[' , ']',验证字符串是否配对合理。

    解法:栈Stack,经典的使用栈的题目。遍历字符串,如果为左括号,将其压入栈中,如果遇到为右括号,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左括号,是合法的继续循环,否则返回false。

    Java: Time: O(n), Space: O(n)

    public static boolean isValid(String s) {
    	HashMap<Character, Character> map = new HashMap<Character, Character>();
    	map.put('(', ')');
    	map.put('[', ']');
    	map.put('{', '}');
    	Stack<Character> stack = new Stack<Character>();
     
    	for (int i = 0; i < s.length(); i++) {
    		char curr = s.charAt(i); 
    		if (map.keySet().contains(curr)) {
    			stack.push(curr);
    		} else if (map.values().contains(curr)) {
    			if (!stack.empty() && map.get(stack.peek()) == curr) {
    				stack.pop();
    			} else {
    				return false;
    			}
    		}
    	} 
    	return stack.empty();
    }

    Java:

    public boolean isValid(String s) {
    	Stack<Character> stack = new Stack<Character>();
    	for (char c : s.toCharArray()) {
    		if (c == '(')
    			stack.push(')');
    		else if (c == '{')
    			stack.push('}');
    		else if (c == '[')
    			stack.push(']');
    		else if (stack.isEmpty() || stack.pop() != c)
    			return false;
    	}
    	return stack.isEmpty();
    }  

    Python:

    class Solution:
        # @return a boolean
        def isValid(self, s):
            stack = []
            dict = {"]":"[", "}":"{", ")":"("}
            for char in s:
                if char in dict.values():
                    stack.append(char)
                elif char in dict.keys():
                    if stack == [] or dict[char] != stack.pop():
                        return False
                else:
                    return False
            return stack == []  

    Python: Time: O(n), Space: O(n)

    class Solution:
        def isValid(self, s):
            stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
            for parenthese in s:
                if parenthese in lookup:  # Cannot use if lookup[parenthese]: KeyError
                    stack.append(parenthese)
                elif len(stack) == 0 or lookup[stack.pop()] != parenthese: # Cannot use not stack
                    return False
            return len(stack) == 0

    Python: wo

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            m = {'(': ')', '[': ']', '{': '}'}
            n = [')', ']', '}']
            for i in s:
                if i in m:
                    stack.append(i)
                elif i in n and stack:
                    if m[stack.pop()] != i:
                        return False
                else:
                    return False
            return len(stack) == 0

    C++:

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> parentheses;
            for (int i = 0; i < s.size(); ++i) {
                if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
                else {
                    if (parentheses.empty()) return false;
                    if (s[i] == ')' && parentheses.top() != '(') return false;
                    if (s[i] == ']' && parentheses.top() != '[') return false;
                    if (s[i] == '}' && parentheses.top() != '{') return false;
                    parentheses.pop();
                }
            }
            return parentheses.empty();
        }
    }; 
    

      

    类似题目:

    [LeetCode] 22. Generate Parentheses

    [LeetCode] 32. Longest Valid Parentheses

    [LeetCode] 241. Different Ways to Add Parentheses

    [LeetCode] 301. Remove Invalid Parentheses

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    动态添加删除控件
    文件下载源码
    poj 1300 欧拉回路、通路 解题报告
    hdu 1232 并查集 或者 深搜
    hdu 2546 01背包问题
    强连通图的判断 hdu 1269
    hdu 2159 二维费用背包问题
    Hdu 3336 kmp+dp解题报告
    hdu 3639 强连通练习使用
    hdu 1712 分组背包问题
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8496903.html
Copyright © 2011-2022 走看看