Thursday, February 8, 2018

[Java][Exercise] CodingBat equalIsNot answer

Question

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

Expected result

 Solution

public boolean equalIsNot(String str) {
  return getAmount(str,"is") == getAmount(str,"not");
}

private int getAmount(String base, String occu){
  int amount = 0;
  int lastInd = 0;
  while(lastInd!=-1){
    lastInd = base.indexOf(occu,lastInd);
    if(lastInd!=-1){
      lastInd += occu.length();
      amount++;
    }
  }
  return amount;
}

Reference

https://stackoverflow.com/questions/767759/occurrences-of-substring-in-a-string
http://codingbat.com/prob/p141736

No comments :

Post a Comment