Problem:
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
Solution:
public boolean equalIsNot(String str) { int len = str.length(); int not = 0; int is = 0; for (int i = 0; i < len; i++) { if (i < len - 2) { String tmp = str.substring(i,i+3); if (tmp.equals("not")) not++; } if (i < len - 1) { String tmp2 = str.substring(i,i+2); if (tmp2.equals("is")) is++; } } if (not == is) return true; else return false; }
public boolean equalIsNot(String str) {
ReplyDeleteint countIs = 0;
int countNot = 0;
str += " ";
for (int i = 0; i < str.length() -2 ; i++) {
if (str.substring(i, i+2).equals("is")) countIs++;
if (str.substring(i, i+3).equals("not")) countNot++;
}
return (countIs == countNot);
}
This is so clever, thank you. I was struggling with a part. And this solved everything. "str += " ";"
Deletepublic boolean equalIsNot(String str) {
ReplyDeleteint diffLengthIs = str.length() - str.replaceAll("is", "").length();
int diffLengthNot = str.length() - str.replaceAll("not", "").length();
int countIs = diffLengthIs / 2;
int countNot = diffLengthNot / 3;
return countIs == countNot;
}
public boolean equalIsNot(String str){
ReplyDeletereturn (str.length() - str.replaceAll("not", "").length()) / 3 == (str.length() - str.replaceAll("is", "" ).length()) / 2;
}
public boolean equalIsNot(String str){
ReplyDeletereturn (str.length() - str.replaceAll("not", "").length()) / 3 == (str.length() - str.replaceAll("is", "" ).length()) / 2;
}
public boolean equalIsNot(String str){
ReplyDeletereturn (str.length() - str.replaceAll("not", "").length()) / 3 == (str.length() - str.replaceAll("is", "" ).length()) / 2;
}
public boolean equalIsNot(String str) {
ReplyDeleteint m=0,n=0;
for(int i=0;i<str.length();i++)
{
if(str.startsWith("is",i))
m++;
if(str.startsWith("not",i))
n++;
}
return m==n;
}
public boolean equalIsNot(String str) {
ReplyDeleteint ci = 0;
int cn=0;
int len = str.length();
for(int i=0; i<len-1; i++){
if(str.substring(i, i+2).equals("is")){
ci++;
}
}
for(int i=0; i<len-2; i++){
if(str.substring(i, i+3).equals("not")){
cn++;
}
}
return ci==cn;
}
public boolean equalIsNot(String str) {
ReplyDeleteint ci = 0;
int cn=0;
int len = str.length();
for(int i=0; i<len; i++){
if(i<len-1){
if(str.substring(i, i+2).equals("is")){
ci++;
}
}
if(i<len-2){
if(str.substring(i, i+3).equals("not")){
cn++;
}
}
}
return ci==cn;
}