0020 - Valid Parentheses
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.
Examples
Input: s = "()" Output: true
Input: s = "()[]{}" Output: true
Input: s = "(]" Output: false
Input: s = "([)]" Output: false
Input: s = "{[]}" Output: true
Constraints:
1 <= s.length <= 104 s consists of parentheses only '()[]{}'.
Java Solution
class Solution {
public boolean isValid(String s) {
if(s.length() < 2) return false;
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c =='(' || c =='[' || c == '{') {
stack.add(c);
if(i == s.length()-1) return false;
} else {
if(stack.isEmpty()) return false;
char check;
check = stack.pop();
if(c == ')' && check != '(') return false;
if(c == '}' && check != '{') return false;
if(c == ']' && check != '[') return false;
}
}
return stack.isEmpty();
}
}
Last updated