This is my method to count the number of parentheses in a string.
public int checkParenthesis(String print, char par){
int num = 0;
for(int i = 0; i<print.length(); i++){
if(print.indexOf(i) == par){
num++;
}
}
return num;
}
It doesn't work. It returns 0.
print
is a random string and par
is a parenthesis.
Inside the loop, set str as paran[i] i.e. the first element of parentheses and again calculate the length of a string. Inside the loop, check IF str[j] = '(' then increment the first by 1 ELSE check IF first = 1 then decrement the first by 1 ELSE increment the last by 1.
Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid, then the stack will be empty once the input string finishes.
For the parentheses to be balanced, each open parenthesis must have a corresponding close parenthesis, in the correct order. For example: ((())) is balanced. (()(()())) is balanced.
You need to use .charAt
to get the current character and compare it with par
:
if(print.charAt(i) == par)
Another way to do this:
for(char c : print.toCharArray()) {
if(c == par) {
num++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With