C++ hash map solution


  • 0
    J
    class Solution {
    public:
        bool isValid(string s) {
        std::unordered_map<char, char> opening_char_table;
        opening_char_table.insert(std::pair<char, char>('(', ')'));
        opening_char_table.insert(std::pair<char, char>('[', ']'));
        opening_char_table.insert(std::pair<char, char>('{', '}'));
        
        std::unordered_map<char, char> enclose_char_table;
        enclose_char_table.insert(std::pair<char, char>(')', '('));
        enclose_char_table.insert(std::pair<char, char>(']', '['));
        enclose_char_table.insert(std::pair<char, char>('}', '{'));
        
        std::stack<char> char_stack;
        size_t str_size = s.length();
        
        if (str_size == 1) {
          return false;
        }
        
        for (int i = 0; i < str_size; ++i) {
          if (opening_char_table.find(s[i]) != opening_char_table.end()) {
            char_stack.push(s[i]);
          } else if (enclose_char_table.find(s[i]) != enclose_char_table.end()) {
            if (char_stack.size() == 0) {
              return false;
            }
            if (char_stack.top() != enclose_char_table[s[i]]) {
              return false;
            }
            char_stack.pop();
          } else {
            // irrelavant character.
            continue;
          }
        }
        
        return char_stack.empty();
      }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.