Valid Closing Parenthesis - Easy
Can use stacks to check for the ClosingParenthesis problem.
One loop through (O(n)
) and Stacks make this fast albeit a teeny bit memory hungry.
- Iterate through, if current char is an opening parenthesis/bracket, then add it to the stack (
put
). - Else if the current is a closing parenthesis, check if its a pair with the opener at the top of the stack (
peak
)- If not pair or stack size is zero then return False,
- else pop the opener from the stack because they’re a pair.
- If stack size is zero then return true (cuz means all openers have been paired), else false.
class Solution {
public boolean pair(Character chr, MyStack stack) {
switch (stack.peak()) {
case '(':
if (chr == ')') {
return true;
}
break;
case '{':
if (chr == '}') {
return true;
}
break;
case '[':
if (chr == ']') {
return true;
}
default:
return false;
}
return false;
}
public boolean isValid(String input) {
MyStack stack = new MyStack();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
stack.push(input.charAt(i));
} else if (input.charAt(i) == ')' || input.charAt(i) == '}' || input.charAt(i) == ']') {
if (stack.size() == 0 || !(pair(input.charAt(i), stack))) {
return false;
} else {
stack.pop();
}
}
}
if (stack.size() == 0) {
return true;
} else {
return false;
}
}
}