[LeetCode] 20. Valid Parentheses 验证括号

 

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

An input string is valid if:java

  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.git

Example 1:github

Input: "()"
Output: true

Example 2:ide

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

Example 3:post

Input: "(]"
Output: false

Example 4:url

Input: "([)]"
Output: false

Example 5:spa

Input: "{[]}"
Output: true

 

这道题让咱们验证输入的字符串是否为括号字符串,包括大括号,中括号和小括号。这里须要用一个栈,开始遍历输入字符串,若是当前字符为左半边括号时,则将其压入栈中,若是遇到右半边括号时,若此时栈为空,则直接返回 false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回 false,代码以下:code

 

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();
    }
}; 

 

Github 同步地址:htm

https://github.com/grandyang/leetcode/issues/20

 

相似题目:

Remove Invalid Parentheses

Different Ways to Add Parentheses

Longest Valid Parentheses

Generate Parentheses

Check If Word Is Valid After Substitutions

 

参考资料:

https://leetcode.com/problems/valid-parentheses/

https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution

https://leetcode.com/problems/valid-parentheses/discuss/9248/My-easy-to-understand-Java-Solution-with-one-stack

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索