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"?
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With