3

Lets say you have a method which takes in a pattern and also an entire String...

The method looks like this:

public int count(String pattern, String input) { 
    int count = 0;
    // How to implement the number of occurrences of the pattern?
} 

So, the inputs could be this:

String input = "sdbwedfddfbcaeeudhsomeothertestddtfdonemoredfdsatdevdb";

String pattern = "ddt";

int result = count(pattern, input);

What would be the most efficient way (in terms of complexity) to iterate and find the occurrences of "ddt"?

PacificNW_Lover
  • 4,746
  • 31
  • 90
  • 144

3 Answers3

3

A simple way to achieve that is to split the String according to the given pattern:

int result = input.split(pattern,-1).length - 1;

How It Works:

.split(pattern, -1)  -> split the String into an array according to the pattern given, -1 (negative limit) means the pattern will be applied as many times as possible.
.length  -> take the length of the array
-1 -> the logic requires counting the splitter (i.e. pattern), so if there is only one occurrence, that will split it into two , when subtract 1 -> it gives the count
Yahya
  • 13,349
  • 6
  • 30
  • 42
2

You can use Pattern and Matcher classes, e.g.:

public int count(String pattern, String input) { 
    int count = 0;
    Pattern patternObject = Pattern.compile(pattern);
    Matcher matcher = patternObject.matcher(input);
    while(matcher.find()){
        count++;
    }
    return count;
} 
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
1

You could do

public int count(String pattern, String input) { 
    int i = (input.length()-input.replace(pattern, "").length())/pattern.length();
    return i;
}

Or even shorter

public int count(String pattern, String input) { 
    return (input.split(pattern, -1).length-1);
}
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34