Valid Parentheses

描述

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

分析

代码

  1. // Valid Parentheses
  2. // 时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. bool isValid (string const& s) {
  6. string left = "([{";
  7. string right = ")]}";
  8. stack<char> stk;
  9. for (auto c : s) {
  10. if (left.find(c) != string::npos) {
  11. stk.push (c);
  12. } else {
  13. if (stk.empty () || stk.top () != left[right.find (c)])
  14. return false;
  15. else
  16. stk.pop ();
  17. }
  18. }
  19. return stk.empty();
  20. }
  21. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/stack-and-queue/stack/valid-parentheses.html