代码改变世界

Valid Parentheses

2015-04-01 10:15  笨笨的老兔子  阅读(147)  评论(0编辑  收藏  举报

有一个由各种括号组成的字符串,判断其是否合法

合法准则即是否成对匹配
(())合法
({])不合法
())(不合法
思路:用栈模拟即可

  1. class Solution {
  2. public:
  3. bool isValid(string s) {
  4. stack<char> stk;
  5. for (size_t i = 0; i < s.size(); i++)
  6. {
  7. if (stk.empty())
  8. stk.push(s[i]);
  9. else if (isPair(stk.top(),s[i]))
  10. {
  11. stk.pop();
  12. }
  13. else
  14. {
  15. stk.push(s[i]);
  16. }
  17. }
  18. return stk.empty() ? true : false;
  19. }
  20. bool isPair(char left, char right)
  21. {
  22. if (left == '(' && right == ')')
  23. return true;
  24. if (left == '[' && right == ']')
  25. return true;
  26. if (left == '{' && right == '}')
  27. return true;
  28. return false;
  29. }
  30. };