Java Program for Anagram Substring Search


Following is an example for Anagram Substring Search in Java −

Example

 Live Demo

public class Demo{
   static final int max_val = 256;
   static boolean compare_vals(char my_arr_1[], char my_arr_2[]){
      for (int i = 0; i < max_val; i++)
      if (my_arr_1[i] != my_arr_2[i])
      return false;
      return true;
   }
   static void search_subs(String my_pattern, String my_text){
      int pat_len = my_pattern.length();
      int txt_len = my_text.length();
      char[] count_pat = new char[max_val];
      char[] count_txt = new char[max_val];
      for (int i = 0; i < pat_len; i++){
         (count_pat[my_pattern.charAt(i)])++;
         (count_txt[my_text.charAt(i)])++;
      }
      for (int i = pat_len; i < txt_len; i++){
         if (compare_vals(count_pat, count_txt))
         System.out.println("The element was found at index " + (i - pat_len));
         (count_txt[my_text.charAt(i)])++;
         count_txt[my_text.charAt(i-pat_len)]--;
      }
      if (compare_vals(count_pat, count_txt))
      System.out.println("The element was found at index " + (txt_len - pat_len));
   }
   public static void main(String args[]){
      String my_text = "ABNFGHABNJGH";
      String my_pattern = "NFGH";
      search_subs(my_pattern, my_text);
   }
}

Output

The element was found at index 2

A class named Demo defines a constant value and a Boolean function that takes in two arrays. It iterates over both the arrays till the constant value is reached. It returns true or false depending on whether the elements in the array that compared were compared were equal or unequal.

Another static function takes in the text and the pattern that needs to be checked for in the text and iterate over the pattern and string. Both the counts of pattern and string are incremented. Again a ‘for’ loop is run and the counts of both the pattern and text are compared. If they are equal, the index is displayed. Otherwise, a relevant message is displayed. In the main class, the pattern and the text are defined and the function is called.

Updated on: 04-Jul-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements