Leetcode--Valid Parentheses

来源:互联网 发布:怎么才可以做淘宝模特 编辑:程序博客网 时间:2024/06/16 05:32

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) {        int i;        vector<char> charVec;        stack<char> charStack;        //底下的第一个循环有些多余了,直接用stack作就可以少一次for循环        for(i=0;i<s.size();i++)        {            if(s[i]=='('||s[i]==')'||s[i]=='{'||s[i]=='}'||s[i]=='['||s[i]==']')            {                charVec.push_back(s[i]);            }        }        if(charVec.size()%2!=0)        {            return false;        }        for(i=0;i<charVec.size();i++)        {            if(charVec[i]=='('||charVec[i]=='{'||charVec[i]=='[')            {                charStack.push(charVec[i]);            }            else            {                if(i==0)                {                    return false;                }                if(charVec[i]==')')                {                    char tt = charStack.top();                    if(tt=='(')                    {                        charStack.pop();                    }                    else                    {                        return false;                    }                }                if(charVec[i]=='}')                {                    char tt = charStack.top();                    if(tt=='{')                    {                        charStack.pop();                    }                    else                    {                        return false;                    }                }                if(charVec[i]==']')                {                    char tt = charStack.top();                    if(tt=='[')                    {                        charStack.pop();                    }                    else                    {                        return false;                    }                }            }                    }        if(!charStack.empty())        {            return false;        }        return true;    }    /*bool Match(vector<char>&aa,int one,int two)    {        if(aa[one])    }*/};

0 0
原创粉丝点击