Given a string, return true if the string "bat" and "ball" appear the same number of times.
MyApproach
I followed the above approach.I have taken the string "bat" and "ball".I searched in the string whether the pattern "bat" exist or not.I checked each character of the original string and compared with the characters of the bat.Similarly I searched for the pattern ball.It will return true When both bat and ball appear same number of times.
Below is my Code with the Output.
public boolean equal(String str)
{
String str1="bat";
String str2="ball";
int l=str.length();
int l1=str1.length();
int l2=str2.length();
if((l<l1) || (l<l2))
{
return false;
}
else
{
int m=0;
int n=0;
int countbat=0;
int countball=0;
int p=0;
int j=0;
str=str.toLowerCase();
str1=str1.toLowerCase();
str2=str2.toLowerCase();
while(j<l)
{
char c=str.charAt(j);
char c1=str1.charAt(p);
if(c==c1){
p++;
if(p==l1){
countbat++;
p=0;
}
}
else{
p=0;
}
j++;
}
while(m<l)
{
char c=str.charAt(m);
char c2=str1.charAt(n);
if(c==c2){
n++;
if(n==l2){
countball++;
n=0;
}
}
else
{
n=0;
}
m++;
}
if(countbat==countball)
return true;
else
return false;
}
}
Parameters Actual Output Expected Output
'bat+ball=cricket' null true
I am not able to get the correct output.Can anyone tell me why?