Leetcode 20. Valid Parentheses
Given a string s
containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. An input string is valid if:
Is the string only limited to the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’? Yes, the problem specifies that the string will contain only these characters.
Is an empty string considered valid? Yes, an empty string should be considered valid since there are no unmatched parentheses.
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else if (c == ')' || c == '}' || c == ']') {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
ValidParentheses validator = new ValidParentheses();
System.out.println(validator.isValid("()")); // true
System.out.println(validator.isValid("()[]{}")); // true
System.out.println(validator.isValid("(]")); // false
System.out.println(validator.isValid("([)]")); // false
System.out.println(validator.isValid("{[]}")); // true
}
}
s
. This is because we iterate through each character in the string once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?