LeetCodeOJ. Valid Parentheses, validparentheses
For questions, see: Https://oj.leetcode.com/problems/valid-parentheses/
Topic Overview
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"(]"And"([)]"Are not.
Solutions
A typical example of data structure. When we read the brackets on the left (including'(','['And'{'), And press into the stack. when reading the parentheses on the right, compare the elements at the top of the stack. If they do not match, the parentheses in the expression cannot be paired.
Problems encountered
[][Status
When the string is read, the elements in the stack may not be empty, and the brackets cannot be completely matched.
[]]Status
When read to 2nd]We will callstack.top()Function. However, the stack is empty, so a Segment Fault exception occurs.
Source code
class Solution {public: bool isValid(std::string s) { for ( auto itr = s.begin(); itr != s.end(); ++ itr ) { if ( *itr == '(' || *itr == '[' || *itr == '{' ) { st.push(*itr); } else if ( *itr == ')' || *itr == ']' || *itr == '}' ) { if ( st.empty() ) { return false; } char topChar = st.top(); if ( *itr == ')' && topChar != '(' ) { return false; } else if ( *itr == ']' && topChar != '[' ) { return false; } else if ( *itr == '}' && topChar != '{' ) { return false; } st.pop(); } } if ( st.empty() ) { return true; } else { return false; } }private: std::stack<char> st;};