Wednesday, August 12, 2009

String Problems

Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in the string (case sensitive).

equalIsNot("This is not") → false
equalIsNot("This is notnot") → true
equalIsNot("noisxxnotyynotxisi") → true

5 comments:

abhijeet said...

we can use counter to iterate over each character in given string and extract substring of length 2 (for "is"). if that is equal to "is", total_is is incremented. Similarly total "not" sub string can be found.


boolean equalIsNot(String value){

int total_is=0;
int total_not=0;

for(int count=0;count< value.length ()-1;count++){
if((value.substring(count,count+2)).equals("is"))
total_is += 1;
}

for(int count=0;count< value.length()-2;count++){
if(value.substring(count,count+3).equals("not"))
total_not += 1;
}

if(total_is==total_not)
return true;
else
return false;
}

Sach said...

One chotu solution can be

boolean equalIsNot(String value){
if(value.split("is").length == value.split("not").length) return true;
else return false;
}

abhijeet said...

ohh.. thats cool

Sach said...

My above solution is a failure in case of a simple string.... :)
isnot

Sach said...

This is because split method works in a weird way...
if string is isnot and you apply split method with token "is" then it returns array of length 2 with elements "" and "not" but if you apply split method on the above string with token "not" it gives you array of length 1 with element "is"... which is very weird
now if we take string notis then it works opposite of above..