• Register
0 votes
232 views

Problem :

I am facing following issue need solution
return true if the string "cat" and "dog" appear the same number of times in the given string
6.9k points

2 Answers

0 votes

Solution :

Following is my answer. It is working as per need. Hope it helps you.

public boolean catDogString(String str) {
  int cat = 0 ;
  int dog = 0 ;
  for(int s  = 0 ; s < str.length()-2; s++){
    String temp = str.substring(s,s+3);
    if(temp.compareTo("cat")==0)
      cat++;
     if(temp.compareTo("dog")==0)
      dog++;
  }
  return cat==dog?true:false;
    
}
36.1k points
0 votes

Solution:

List of  few critical problems in your code

1. Your call to substring() fetches a string of size 2. That string can never be cat nor dog. Change the second parameter in the               method call to i + 3 to get 3 characters.

 

2. Your call to substring() will throw an IndexOutOfRangeException, as i approaches the end of the length of the input string.              Make sure you do not ask for a substring that "overflows" the length of the input string. One way to fix this bug, would be to change        the conditional expression in your for loop to i < str.length() - 2.

 

3. The return value of your method will always be true. In the case where dogAnswer != catAnswer you return exactly that                    expression - which will resolve to true. A possible solution: Merge the two return statements into return dogAnswer ==          catAnswer.

Additionally, there are a few things you could do to make your code simpler:

1. There really is no need to copy cat_Count into catAnswer and dog_Count into dogAnswer. Throw away two of the variables, and        use the other pair exclusively.

Here's an "All Correct" solution that uses split. The -1 is used to preserve trailing empty strings.

int count(String needle, String haystack) {
  return haystack.split(needle, -1).length - 1;
}

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

You will want to iterate each character in your string and then check to see if the substring is equal to either cat or dog and increments the counts.

public boolean catDog(String str) {

  int end = str.length();
  int cDog = 0;
  int cCat = 0;

  // We don't need to go to the end because cat/dog are 3 characters long each. So we can avoid extra checks.
  for (int i=0; i < end-2; i++) {
        if(str.substring(i, i+3).equals("cat")) {
          cCat++;
        } else if(str.substring(i, i+3).equals("dog")) {
          cDog++;
        }  
   }

   return cCat == cDog ? true : false;
}

A solution with less duplication would be to write a function that counts occurrences of a substring within a string, then call that function with the string and "cat", and with the string and "dog", and return whether the two counts agree.

public boolean catDog(String str) {
    int cdog = 0;
    int ccat = 0;

    for (int i = 0; i < str.length()-2; i++)
    {
        if (str.charAt(i)== 'c' && str.charAt(i+1)== 'a' && str.charAt(i+2)== 't')
        {
            ccat++;
        }

        else if(str.charAt(i) == 'd' && str.charAt(i+1)== 'o' && str.charAt(i+2)== 'g')
        {
            cdog++;
        }

    }

    if (cdog == ccat)
        return true;

    else
        return false;
}

 

15.3k points

Related questions

0 votes
1 answer 77 views
77 views
Problem : I am trying to print every string in Reverse Double Character way (e.g. string -> ggnniirrttss) import java.util.Scanner; public class ReverseDoubleCharecters { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter ... I get as follows: ss tt rr ii nn gg All double characters are printed on new lines. Anybody has the solution on this?
asked Nov 22, 2019 peterlaw 6.9k points
0 votes
2 answers 97 views
97 views
Problem : How to count the number of occurrences of a character in a string in java
asked Oct 23, 2019 peterlaw 6.9k points
0 votes
1 answer 25 views
25 views
Problem : I am very new to Java Programming and currently I am stuck with the following doubt related to Strings. How to determine if two strings are permutations of each other? Any solution on my above doubt will be appreciated.
asked Dec 25, 2019 alecxe 7.5k points
2 votes
1 answer 14 views
14 views
Problem: I just started learning java and solving problems from various online websites. Stuck on a problem saying, count how many times a substring appears in a string java. This problem is beyond my understanding. I found Kodlogs very helpful and friendly environment ... possible solution (with code snippet) would be great for me, and I must recognize your help. Thanks in advance, mate.
asked Mar 25 Gavin 15.2k points
1 vote
1 answer 192 views
192 views
Problem: I am new in python programming and I have been doing a course on it as a new comer I tried to repeat some char in a string. I wrote a code : def Work(str): for i in range(len(str)): return i * 2 But it does not work . how can I do this?
asked Apr 3 LizzyM 5.7k points