Improved Naive Pattern Searching for Distinct

PHOTO EMBED

Tue Feb 08 2022 11:42:13 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #string #patternsearching #index #improvednaive #distinct

import java.util.*;
import java.io.*;
  
class GFG { 
       
    static void patSearchinng(String txt,String pat)
    {
        int m=pat.length();
        int n=txt.length();
        for(int i=0;i<=(n-m); )
        {
            int j;
            for(j=0;j<m;j++)
                if(pat.charAt(j)!=txt.charAt(i+j))
                    break;
            
            if(j==m)
                System.out.print(i+" ");
            if(j==0)
                i++;
            else
                i=(i+j);
        }
    }
  
    public static void main(String args[]) 
    {   String txt = "ABCABCD";String pat="ABCD";
        System.out.print("All index numbers where pattern found: ");
        patSearchinng(txt,pat);  
    } 
} 
content_copyCOPY

Given a pattern with distinct characters and a text, we need to print all occurrences of the pattern in the text. This code talks about improved Naive pattern searching with Theta(n) time complexity. Input : -------- Text = "ABCABCD" Pattern ="ABCD" Output: --------- All index numbers where pattern found: 3