0ms C++ taking advantage of ASCII pattern


  • 2
    R

    Basic idea:

    1. use stack to keep store and only store left parenthese

    2. ASCII code table as below. The difference between each pair is either 1 or 2.
      {}->123/125
      []->91/93
      ()->40/41

    3. if match, pop out; otherwise, return false;

      class Solution {
      public:
      bool isValid(string s) {
      stack<char> st;
      for(auto&& x: s){
      if(x=='(' || x == '[' || x == '{') st.push(x);
      else
      if(st.empty() || (abs(x-st.top())>2)) return false;
      else st.pop();
      }
      return st.empty();
      }
      };


Log in to reply
 

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