LeetCode : Valid Parentheses

来源:互联网 发布:2017php笔试 编辑:程序博客网 时间:2024/05/02 00:13

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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        stack<char> stk;        char map[256];        map['('] = ')';        map['['] = ']';        map['{'] = '}';        for(int i = 0; i< s.size(); ++i){            char c = s[i];            if(c == '(' || c == '[' ||c == '{'){                stk.push(c);            }            else{                if(stk.empty())                    return false;                char l = stk.top();                if(map[l] == c){                    stk.pop();                }                else{                    return false;                }            }        }        if(!stk.empty()){            return false;        }        return true;    }};