[leetcode]20. Valid Parentheses

来源:互联网 发布:it服装 编辑:程序博客网 时间:2024/06/07 03:43

class Solution {public:    bool isValid(string s) {        int length=s.length();        if(length==0) return true;        if(length%2 != 0)  return false;                char flag[6]={'(',')','{','}','[',']'};        stack<char> a;        a.push(s[0]);                for(int i=1; i<length; i++)        {            if(a.empty())                a.push(s[i]);            else            {                char tmp = a.top();                if( ((tmp==flag[0])&&(s[i]==flag[1])) || ((tmp==flag[2])&&(s[i]==flag[3])) || ((tmp==flag[4])&&(s[i]==flag[5])) )                    a.pop();                else                    a.push(s[i]);            }        }                if(a.empty())            return true;        else            return false;    }};

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

The brackets must close in the correct order,"()" and "()[]{}" are all valid but "(]" and "([)]" are not valid

最开始看到这个问题以为是规律给出来的,比如说是这样的:(){}[](),这样的理解是不对的,([])这样的结果也是对的

所以,用栈这种数据结构来处理这种问题是最方便的,代码如下


0 0
原创粉丝点击