[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