Here’s an function implemented in Java to check whether a string contains balanced parentheses.
Examples
isBalanced("((()))")returnstrueisBalanced("(()()())")returnstrueisBalanced("(()()()")returnsfalseisBalanced("()())")returnsfalse
Implementation
/**
* Checks if the specified string has balanced parentheses.
*
* @param str
*
* @return True, if the parentheses are balanced, false otherwise.
*/
public static boolean isBalanced(String str) {
// Define the sum of the brackets.
int sum = 0;
// Loop through each character in the string.
for(int i=0; i < str.length(); i++) {
// If the character is an open bracket, add 1.
// If the character is a closed bracket, remove 1.
if(str.charAt(i) == '('){
sum += 1;
} else if(str.charAt(i) == ')'){
sum -= 1;<br />
}
}
// The total sum must be 0, if the brackets are balanced.
// Otherwise, they are not balanced.
return sum == 0;
}