4/03/2014

Leetcode -- Valid Parentheses

class Solution {  
 public:  
   bool isValid(string s) {  
     vector<char> stack;  
     unordered_map<char, char> map{  
       {')','('},  
       {']','['},  
       {'}','{'}  
     };  
     for(auto c:s) {  
       if(c == '(' || c== '[' || c == '{') {  
         stack.emplace_back(c);  
       } else if(map.count(c) > 0 && stack.size() && map[c] == stack[stack.size() - 1]) {  
         stack.pop_back();    
       } else {  
         return false;  
       }  
     }  
     return !stack.size();  
   }  
 };  

No comments: