leetcode—Valid Parentheses

1.问题描述

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.

2.解法分析

典型的栈用法。

class Solution {
public:
    bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<char> myStack;
        map<char,char>dict;
        dict.insert(make_pair('(',')'));
        dict.insert(make_pair('[',']'));
        dict.insert(make_pair('{','}'));
        
        for(int i=0;i<s.length();++i)
        {
            if(s[i]=='('||s[i]=='['||s[i]=='{')myStack.push_back(s[i]);
            else
                if(s[i]==')'||s[i]==']'||s[i]=='}')
                {
                    if(myStack.empty())return false;
                    if(dict[myStack.back()]==s[i])myStack.pop_back();
                    else return false;
                }
        }
        
        if(myStack.empty())return true;
        return false;
        
    }
};
posted @ 2013-08-22 22:16  曾见绝美的阳光  阅读(166)  评论(0编辑  收藏  举报