zoukankan      html  css  js  c++  java
  • 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.

    思路:这道题使用栈作为辅助空间。首先如果遍历到左括号则压入栈中,然后当遍历到")"或者"}"或者"]",则做出判断,如果找到对应的左括号时,将这个左括号出栈。依次类推,三个判断条件,随时判断栈是否为空。最后循环遍历结束后,判断栈是不是为空,如果为空则为真,否则就为假。

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> str;
            int nSize=s.size();
            if(nSize==0)
                return true;
            for(int i=0;i<nSize;i++)
            {
                if(s[i]=='('||s[i]=='['||s[i]=='{')
                    str.push(s[i]);
                else
                {
                    if(s[i]==')')
                    {
                        if(!str.empty()&&str.top()=='(')
                            str.pop();
                        else
                            return false;
                    }
                    if(s[i]==']')
                    {
                        if(!str.empty()&&str.top()=='[')
                            str.pop();
                        else
                            return false;
                    }
                    if(s[i]=='}')
                    {
                        if(!str.empty()&&str.top()=='{')
                            str.pop();
                        else
                            return false;
                    }
                }
            }
            if(str.empty())
                return true;
            else
                return false;
        }
    };
  • 相关阅读:
    按回车键提交表单
    Access数据库类型及属性
    Problem 1002
    问题 1003
    Problem 1003
    Switch Game(摘自LP学C++)
    1006
    膜拜蛇形矩阵
    A == B?
    Rectangles
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3654633.html
Copyright © 2011-2022 走看看