Sample Problem: Pattern Searching

 Pattern Searching - a Basic Problem to Find Substrings in a Text

Pattern Searching is a basic problem in computer science that helps us find a specific word or substring in a given text. In this problem, we are given a text and a word, and we need to find all the positions where the word occurs in the text.

For example, let's say we have the text "I love eating apples, apples are my favorite fruit." and we want to find the positions where the word "apples" occurs. The answer would be positions 9 and 16, since the word "apples" appears at these two positions in the text.

To solve this problem, we can use the indexOf() function in Java, which finds the first occurrence of a pattern in a text from left to right. We can use this function to find the first occurrence of the word in the text, and then continue to find all other occurrences of the word by starting from the next position.

For instance, if we search for the word "geeks" in the text "geeks for geeks", we will find it at positions 0 and 10.

Here's the Java code to implement this approach:

typescript
import java.util.*; class PatternSearch { static void findPositions(String text, String word) { int pos = text.indexOf(word); while(pos >= 0) { System.out.print(pos + " "); pos = text.indexOf(word, pos + 1); } } public static void main(String args[]) { String text = "geeks for geeks"; String word = "geeks"; findPositions(text, word); } }

The output of this code will be "0 10", which are the positions where the word "geeks" appears in the text.

In summary, the pattern searching problem is a basic but useful problem in computer science that helps us find substrings in a given text. We can use the indexOf() function in Java to solve this problem, by finding the first occurrence of the word and then continuing to find all other occurrences.

Previous Post Next Post