美文网首页
LeetCode 20. Valid Parentheses

LeetCode 20. Valid Parentheses

作者: 洛丽塔的云裳 | 来源:发表于2020-04-04 22:14 被阅读0次

0. 题目

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
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

1. C++版本

思想:其实很简单,就是使用栈的思想,将所有括号入栈,当栈顶元素是"(",当前元素是")",那么就将栈里面的"("弹出,依次类推处理"[]","{}"。最后如果栈空,说明所有括号匹配

  bool isValid(string s) {
      stack<char> mystack;
        char topBracket;
        for (int i=0; i<s.size(); ++i) {
             if (!mystack.empty())
                 topBracket = mystack.top();
             if ((s[i]==')' && topBracket=='(') || (s[i]==']' && topBracket=='[') || (s[i]=='}' && topBracket=='{'))
                 mystack.pop();
             else
                 mystack.push(s[i]);
        }

       if (mystack.empty())
           return true;
       else
           return false;
    }

2. python版本

    def isValid(s):
        """
        :type s: str
        :rtype: bool
        """
        mystack = []
        topBracket = ''
        for index, bracket in enumerate(s):
            if mystack:
                topBracket =  mystack[-1]
            if (bracket==')' and topBracket=='(') or (bracket==']' and topBracket=='[') or (bracket=='}' and topBracket=='{'):
                mystack.pop()
            else:
                mystack.append(bracket)
        if mystack:
            return False
        return True

相关文章

网友评论

      本文标题:LeetCode 20. Valid Parentheses

      本文链接:https://www.haomeiwen.com/subject/qzcsphtx.html