Advanced String Manipulation Question
You are given a string sentence
and a string word
, both containing only lowercase alphabetical characters. You need to implement a function countOccurrences(sentence: str, word: str) -> int
that counts the number of occurrences of the word
in the sentence
, considering both exact matches and matches that differ by a single character.
Additionally, you should consider only the occurrences of the word that are in the same order as the characters in the word
. For example, if word
is "abc" and sentence
is "abbcac", the only valid occurrence would be "abbc" because it follows the order of characters in "abc".
Please write the function countOccurrences
and provide step-by-step explanation.
public class StringManipulation {
public static int countOccurrences(String sentence, String word) {
int count = 0;
int wordPointer = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == word.charAt(wordPointer)) {
wordPointer++;
if (wordPointer == word.length()) {
count++;
wordPointer = 0;
}
} else {
wordPointer = 0;
if (sentence.charAt(i) == word.charAt(0))
wordPointer = 1;
}
}
return count;
}
public static void main(String[] args) {
String sentence = "abbcbac";
String word = "abc";
int occurrences = countOccurrences(sentence, word);
System.out.println("Occurrences: " + occurrences);
}
}
count
variable to keep track of the number occurrences of the word.wordPointer
variable to keep track of the index within the word
string.sentence
string using a for loop.word
string using sentence.charAt(i) == word.charAt(wordPointer)
.
wordPointer
by 1.wordPointer
becomes equal to the length of word
, it means a full occurrence of word
is found in sentence
. Increment the count
by 1 and reset wordPointer
to 0.wordPointer
to 0.
word
using sentence.charAt(i) == word.charAt(0)
.wordPointer
to 1 to start checking the next character in the next iteration, since it could potentially be a partial match.sentence
, return the final count
.In the given question, the main
function demonstrates how to use the countOccurrences
function. It initializes the sentence
and word
variables, then calls the countOccurrences
function passing these variables and stores the result in the occurrences
variable. Finally, it prints the value of occurrences
to the console.