Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
Constraints:
1 <= s.length <= 104s consists of parentheses only '()[]{}'.class Solution {
public boolean isValid(String s) {
Stack<Character> stk = new Stack<>();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
switch (c) {
case ')' -> {
if (!stk.isEmpty() && stk.peek() == '(')
stk.pop();
else
return false;
}
case '}' -> {
if (!stk.isEmpty() && stk.peek() == '{')
stk.pop();
else
return false;
}
case ']' -> {
if (!stk.isEmpty() && stk.peek() == '[')
stk.pop();
else
return false;
}
default -> stk.push(c);
}
}
return stk.isEmpty();
}
}