[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

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();
    }
}
目录
相关文章
|
4月前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode 367. Valid Perfect Square
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
92 0
LeetCode 367. Valid Perfect Square
LeetCode 301. Remove Invalid Parentheses
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。 说明: 输入可能包含了除 ( 和 ) 以外的字符。
65 0
LeetCode 301. Remove Invalid Parentheses
LeetCode 242. Valid Anagram
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
74 0
LeetCode 242. Valid Anagram
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
75 0
LeetCode 241. Different Ways to Add Parentheses
|
canal
LeetCode 125. Valid Palindrome
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
86 0
LeetCode 125. Valid Palindrome
|
算法
LeetCode 65. Valid Number
验证给定字符串是否可以解释为十进制数。
88 0
LeetCode 65. Valid Number
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
103 0
Leetcode-Easy 20. Valid Parentheses
LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 有效字符串需满足: 左括号必须用相同类型的右括号闭合。
757 0