Given a string s 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.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Constraints:
1 <= s.length <= 104
s consists of parentheses only ‘()[]{}’.
Solution1 Stack
-
Maintain a stack s ,and maintain a hash map m like this:
{
{“{”, “}”},
{“[”,“]”},
{“(”,“)”}
} -
if the size of the string is an odd number then return false;
-
Loop over the string,
-
if the current character is an open bracket, then push it into s
-
if it is a close bracket, then get the top element of s, denoted as variable p, if m.at(p) does not equal the current character then return false, otherwise
-
Pop the top of the stack。 if s is empty after the looping is done then return true, otherwise return false