Valid Parenthesis Java Program
In this Java code snippet, we have a solution to check if the parentheses in a given string are balanced or not. The code uses a stack to keep track of the opening brackets and verifies if the closing brackets match with the last opening bracket.
Code Explanation:
The code provides two helper methods:
- isOpeningBracket(char c): This method checks if the character is an opening bracket - '(', '{', or '['.
- isMatchingPair(char c, char popChar): This method verifies if the current closing bracket character 'c' matches with the last opening bracket character 'popChar' in the stack.
The isValid(String s) method is the main function that checks if the given string 's' contains balanced parentheses. It iterates through each character of the string and handles opening and closing brackets accordingly.
- If an opening bracket is encountered, it is pushed onto the stack.
- If a closing bracket is encountered, the code checks if the stack is empty (unbalanced) or if the current closing bracket matches the last opening bracket in the stack. If not, the parentheses are not balanced, and the method returns false.
- If all characters are processed successfully and the stack is empty, the method returns true, indicating that the parentheses are balanced.
Java Code:
import java.util.Stack;
class Solution {
public boolean isOpeningBracket(char c){
return (c == '(' || c == '{' || c == '[' );
}
public boolean isMatchingPair(char c, char popChar){
if(c == '}' && popChar == '{' ) return true;
if(c == ')' && popChar == '(' ) return true;
if(c == ']' && popChar == '[' ) return true;
return false;
}
public boolean isValid(String s) {
Stack<Character> charStack = new Stack<Character>();
for(char ch : s.toCharArray()){
if(isOpeningBracket(ch)){
charStack.push(ch);
} else {
if(charStack.isEmpty()){
return false;
}
char popChar = charStack.pop();
if(!isMatchingPair(ch, popChar)){
return false;
}
}
}
return charStack.isEmpty();
}
}
Copy and paste the provided Java code into your IDE to see how it efficiently checks for balanced parentheses in a string. You can also integrate this code into your projects where parentheses matching is needed, such as expression evaluation or syntax validation.
Remember to credit the source if you use this code in your projects.
0 Comments