Find nth Occurrence

Find nth Occurrence

This problem comes from a given, but unimplemented, method from the 2017 AP Computer Science exam called Phrase.

In one part you were tasked with replacing the \(n^{th}\) occurrence of one string within another string. And they gave you a method findNthOccurrence to help you out.

But the implementation for findNthOccurrence was not shown. So for this coding challenge, that's you job.

As an example, the call findNthOccurrence( "dogdogdogdog", "dog", 2 ) should return 3 because the 2nd "dog" starts at index 3. findNthOccurrence( "dogdogdogdog", "dog", 3 ) would return 6.

If find does not occur in str the method should return -1. Likewise if there is no \(n^{th}\) occurrence the method should also return -1.

findNthOccurrence("dogdogdogdog", "dog", 1) => 0
findNthOccurrence("dogcatdogdodgdogddd", "dog", 3) => 13
findNthOccurrence("dogdogdog", "dag", 1) => -1
findNthOccurrence("catcatcat", "dog", 3) => -1
findNthOccurrence("fishchickendogcatplatypus", "chicken", 5) => -1

Ask Question