Given a string containing just the characters‘(‘
,‘)‘
,‘{‘
,‘}‘
,‘[‘
And‘]‘
, Determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"Output: true
Example 2:
Input: "()[]{}"Output: true
Example 3:
Input: "(]"Output: false
Example 4:
Input: "([)]"Output: false
Example 5:
Input: "{[]}"Output: true
Idea: Because I recently used the learning stack, I used the stack to solve this problem. Traverse the string. If the matched (, {, [.).],} is pushed into the stack.
If the above characters are not matched, the stack goes out to check whether the top element of the stack is equal to the corresponding characters.
class Solution {public: bool isValid(string s) { std:stack<char> st; for(char i : s){ if(i == ‘(‘){ st.push(‘)‘); }else if(i == ‘[‘){ st.push(‘]‘); }else if(i == ‘{‘){ st.push(‘}‘); } else { if(st.empty()){ return false; }else{ char top = st.top(); st.pop(); if(top != i){ return false; } } } } return st.empty(); }};
Leetcode-20 valid parentheses.