[LeetCode] 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 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         stack<char> st;
 7         
 8         for(int i = 0; i < s.size(); i++)
 9             if (s[i] == ')' || s[i] == ']' || s[i] == '}')
10             {
11                 if (st.empty())
12                     return false;
13                 else
14                 {
15                     char c = st.top();
16                     st.pop();
17                     if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}'))
18                         return false;
19                 }
20             }
21             else
22                 st.push(s[i]);
23                 
24         return st.empty();
25     }
26 };


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM