Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.ta#### Example 1:
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
Input: s = "([)]"
Output: false
Input: s = "{[]}"
Output: true
- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
- java
/*
Success Details:
Runtime: 1 ms, faster than 99.15% of Java online submissions for Valid Parentheses.
Memory Usage: 36.4 MB, less than 86.39% of Java online submissions for Valid Parentheses.
*/
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '[') {
stack.push(']');
} else if (c == '{') {
stack.push('}');
} else {
if (stack.empty() || c != stack.pop()) {
return false;
}
}
}
return stack.empty();
}
}