[Leetcode] 20. Valid Parentheses(Stack)

来源:互联网 发布:coach淘宝代购 编辑:程序博客网 时间:2024/06/15 00:37

括号匹配问题,使用栈的特点,匹配则出栈,否则入栈,最后栈为空则全部匹配。代码如下:

 1 class Solution { 2 public: 3     bool isValid(string s) { 4         stack<char> T; 5         for(int i = 0;i < s.length();i ++) 6         { 7             if((T.empty()) || (s[i] == T.top()) || abs(s[i] - T.top()) > 2) 8             { 9                 T.push(s[i]);10             }11             else T.pop();12         }13         if(T.empty())14             return true;15         else16             return false;17     }18 };