-2

Return true if the string "cat" and "dog" appear the same number of times in the given string.

catDog("catdog") → true

catDog("catcat") → false

catDog("1cat1cadodog") → true

public boolean catDog(String str) {
  int countCat=0;
  int countDog=0;

  for(int i=0;i<str.length()-3;i++){
    if(str.substring(i).startsWith("cat")){
      countCat++;
    }
    if(str.substring(i).startsWith("dog")){
      countDog++;
    }
  }
  if(countCat==countDog){
    return true;
  }
  else{
    return false;
  }
}

I am having trouble writing this method. Does anybody know why my code doesn't work correctly? Edit: The code compiles, however it gives the wrong output. For example if i put in "catdog" it returns false.

  • Have you checked, that you iterate the correct amount of times? Because you currently don't. – Tom Dec 16 '16 at 12:34
  • 1
    I got it, I got it. I was working with substring(i,i+3) and forgot to change the length of iteration steps when I started using startsWith. – DerDieDasEhochWas Dec 16 '16 at 13:06

4 Answers4

1

with the examples you posted, its because of your for loop which should be for(int i=0;i<str.length();i++){. you can also use str.length()-1 and str.length()-2 to get the right result. -3 will give the wrong result. little example: string is catdog1dog. result should be false. lets have a look at the substring which will be created with -3:

catdog1dog
atdog1dog
tdog1dog
dog1dog
og1dog
g1dog
1dog

as you can see with -3 the last substring is wrong and therefore the result too. that is because if you look at substring, you will see that the start is at char 0 and not at 1 therefore str.length()-1 is the last character in your string. sorry if my explanations isn't that good

XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
0

As suggestsed in this question, I would recomment using StringUtils.countMatches from Apache Commons Lang?

Credit to @A_M

Community
  • 1
  • 1
alexdriedger
  • 2,884
  • 2
  • 23
  • 30
0

Although your problem can be solved through other strategies, I think you might only subtract 2 to str.length() instead of 3.

I hope be useful!

0

I would do something like this:

public boolean catDog(String str){
    return countWords(str, "cat") == countWords(str, "dog");
}


private int countWords(String original, String word){
    int counter = 0;
    boolean searching = true;
    while(searching){
        if(original.indexOf(word) >= 0){
            counter++;
            original = original.substring(original.indexOf(word) + word.length());
        }
        else{
            searching = false;
        }
    }
    return counter;
}
cralfaro
  • 5,822
  • 3
  • 20
  • 30