[LeetCode] Valid Parentheses

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Subscribe to see which companies asked this question

解题思路

借助栈来实现:

  • 如果为左括号则入栈;
  • 如果为右括号, 若:
    • 栈顶为与之匹配的左括号,则出栈。
    • 否则,返回false。
  • 最后,返回stack.empty()

实现代码

C++:

// Runtime: 0 ms
class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char> mymap = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
        stack<char> mystack;
        for (int i = 0; i < s.length(); i++)
        {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{')
            {
                mystack.push(s[i]);
            }
            else if (!mystack.empty() && (mymap[mystack.top()] == s[i]))
            {
                mystack.pop();
            }
            else
            {
                return false;
            }
        }

        return mystack.empty();
    }
};

Java:

// Runtime: 2 ms
public class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<Character, Character>();
        Stack<Character> stack = new Stack<Character>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                stack.push(s.charAt(i));
            }
            else if (!stack.empty() && map.get(stack.peek()).equals(s.charAt(i))) {
                stack.pop();
            }
            else {
                return false;
            }
        }

        return stack.empty();
    }
}
时间: 2024-11-27 04:17:53

[LeetCode] Valid Parentheses的相关文章

[LeetCode] 20.Valid Parentheses

[题目] Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]

[LeetCode]32.Longest Valid Parentheses

题目 Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example i

LeetCode 32 Longest Valid Parentheses(最长有效括号)(*)

翻译 给定一个仅仅包含"("或")"的字符串,找到其中最长有效括号子集的长度. 对于"(()",它的最长有效括号子集是"()",长度为2. 另一个例子")()())",它的最长有效括号子集是"()()",其长度是4. 原文 Given a string containing just the characters '(' and ')', find the length of the l

[LeetCode] Valid Parenthesis String 验证括号字符串

Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesi

Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is &

[LeetCode] Valid Palindrome II 验证回文字符串之二

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. N

leetcode 20 Valid Parentheses 括号匹配

Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]"

LeetCode 20 Valid Parentheses(有效的括号)

翻译 给定一个只包含'(', ')', '{', '}', '[' 和']'的字符串,判断这个输入的字符串是否是有效的. 括号必须在正确的形式下闭合,"()" 和"()[]{}" 是有效的,但是 "(]" 和"([)]" 则不是. 原文 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the

Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]"