algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

valid-parenthesisV2.cpp (635B)


      1 class Solution {
      2 public:
      3     bool isValid(string s) {
      4         vector<char> stack = {};
      5 
      6         unordered_map<char, char> mapping = {
      7             {'(', ')'},
      8             {'{', '}'},
      9             {'[', ']'}
     10         };
     11 
     12         for (char value: s) {
     13            if(mapping.find(value) != mapping.end()){
     14             stack.push_back(value);
     15            }
     16            else {
     17             
     18             if (stack.size() == 0) return false;
     19 
     20             char lastOpening = stack.back();
     21             stack.pop_back();
     22 
     23             if (mapping[lastOpening] != value) return false;
     24 
     25            }
     26         }
     27 
     28         return stack.size() == 0;
     29     }
     30 };