LeetCode : Valid Parentheses

问题:

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

C++参考代码:

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char,int> m;
        vector<int> v;
        m['('] = 1;
        m[')'] = -1;
        m['{'] = 2;
        m['{'] = -2;
        m['{'] = 3;
        m['{'] = -3;
        for(int i=0;i<s.length();i++){
            if(m[s[i]]>0){
                v.push_back(m[s[i]]);
            }else if(!v.empty() &&( m[s[i]] + v[v.size()-1] )== 0){
                v.pop_back();
            }else{
                return false;
            }
        }
        if(v.empty()){
            return true;
        }else {
            return false;
        }
       
    }
};

posted @ 2018-09-19 19:00  wangliuliu  阅读(74)  评论(0编辑  收藏  举报