In this post, we will see Valid Parenthesis with stack.
This solution uses a counter to keep track of the balance of parentheses. Whenever an opening parenthesis is encountered, the counter is incremented. When a closing parenthesis is encountered, the counter is decremented. If the counter is zero when a closing parenthesis is encountered, the function returns false. At the end, if the counter is zero, the parentheses are balanced and the function returns true.
public class ValidParenthesis {
public boolean isValid(String s) {
int count = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
count++;
} else if (c == ')') {
if (count == 0) {
return false;
}
count--;
} else if (c == '{') {
count++;
} else if (c == '}') {
if (count == 0) {
return false;
}
count--;
} else if (c == '[') {
count++;
} else if (c == ']') {
if (count == 0) {
return false;
}
count--;
}
}
return count == 0;
}
public static void main(String[] args) {
ValidParenthesis validParent= new ValidParenthesis();
System.out.println(validParent.isValid("{}((())){}"));
}
}