• Register
0 votes
1k 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 5 3
6,930 points

Please log in or register to answer this question.

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;
    
}
9 7 4
38,600 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;
}

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 28 views
28 views
Problem: return true if the string "cat" and "dog" appear the same number of times in the given string.
asked Feb 23 Muneeb Saadii 130k points
0 votes
1 answer 10 views
10 views
Problem: I wrote the following Java code, and it returned a time out error. I'm not exactly sure what that means nor why the code doesn't run public int countHi(String str) { int pos = str.indexOf("hi"); int count = 0; while(pos!=-1) { count++; pos = str.substring(pos).indexOf("hi"); } return count; } I know an alternative solution, using a for loop but I really thought this would work too.
asked Apr 25 Humaira ahmed 50.7k points
0 votes
1 answer 199 views
199 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
1 answer 6 views
6 views
Problem: I'm having trouble processing this error: It is required that the operation be exported or include an intent-filter &ldquo;Count total number of times each alphabet appears in the string java program code with example&rdquo;?
asked Mar 29 tuhin1 48.9k points
0 votes
1 answer 601 views
601 views
Problem : I am completely stuck on this problem Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False I know the basic idea but I am unable to implement it. ... this, eg. graph, search? def has22(mynums): for l in mynums: if ( (mynums[l] = 2) and (mynums[l+1] = 2) ) return True return False
asked Dec 10, 2019 alecxe 7.5k points
1 vote
1 answer 1.2K views
1.2K 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, 2020 LizzyM 6.1k points
0 votes
1 answer 4 views
4 views
Problem: How to check if first character of a string is a number?
asked Apr 17 sumaiya simi 43.9k points
0 votes
1 answer 2 views
2 views
Problem: I came across with this problem > If you add a number and a string the result will be which of the following
asked 4 days ago ummeshani 8.8k points
0 votes
1 answer 1 view
1 view
Problem: I'm trying to solve this exercise of finding the number that appears an odd number of times in an array. I have this so far but the output ends up being an integer that appears an even number of times. For example, the number 2 appears 3 times and the number 4 appears 6 times, but the ... count = tempCount; element = array[j]; } } } } return element; } oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
asked 2 days ago muktaa 34.4k points