Valid Parentheses
Sergei Golitsynhttps://leetcode.com/problems/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.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]" Output: false
Solution:
Ooooh, that is one of the popular types of interview problems. I saw this problem more than 3-4 times on the interviews.
We need to validate parentheses. We should find a way how to check open and close chars.
But how can we do it? Stack. The stack will help us. We will put open char into the stack and "pop" it if the current char is close.
Is it clear? Yeah, that is easy to understand.
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i ++){
char cur = ch[i];
if(cur == '(' || cur == '{' || cur == '['){
stack.push(cur);
} else {
if (stack.isEmpty()){
return false;
}
if(cur == ')'){
if(stack.peek() == '('){
stack.pop();
} else {
return false;
}
}
if(cur == '}'){
if(stack.peek() == '{'){
stack.pop();
} else {
return false;
}
}
if(cur == ']'){
if(stack.peek() == '['){
stack.pop();
} else {
return false;
}
}
}
}
return stack.isEmpty();
}