Leetcode 之Length of Last Word(38)

做法很巧妙。分成左右两个对应的部分,遇到左半部分则入栈,遇到右半部分则判断对应的左半部分是否在栈顶。注意最后要判断堆栈是否为空。

 bool isValid(const string& s)
      {
          string left = "([{";
          string right = ")]}";
          stack<char> stk;

          for (auto c : s)
          {
              if (left.find(c) != string::npos)
              {
                  stk.push(c);
              }
              else
              {
                  if (stk.empty() || stk.top() != left[right.find(c)])
                      return false;
                  else
                      stk.pop();
              }
          }

          return stk.empty();
      }
View Code
原文地址:https://www.cnblogs.com/573177885qq/p/5531360.html