How would you write this algorithm recursively? via /r/learnprogramming


How would you write this algorithm recursively?

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

My iterative code:

public boolean catDog(String str) { int dogCount = 0; int catCount = 0; for(int i = 0; i < str.length()-2; i++){ if(str.substring(i,i+3).equals("cat")){ catCount++; } if(str.substring(i,i+3).equals("dog")){ dogCount++; } } return catCount == dogCount; } 

The reason I'm confused by how you would do this recursively is because you're returning a boolean overall but to keep track of how many of dog and cat you'd have to return the numbers of dogs and cats right? Like if the problem were to return how many dogs or cats I could do that.

Submitted July 14, 2017 at 01:22PM by eatingpoopinrobarts
via reddit http://ift.tt/2tU99yF

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s