以下是Java中的Anagram Substring Search的示例-
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); } }
输出结果
The element was found at index 2
名为Demo的类定义一个常数值和一个接受两个数组的布尔函数。遍历两个数组,直到达到常数。根据比较数组中被比较的元素是相等还是不相等,它返回true或false。
另一个静态函数接收需要在文本中检查的文本和模式,并遍历模式和字符串。模式和字符串的计数都增加。再次运行“ for”循环,并比较模式和文本的计数。如果它们相等,则显示索引。否则,将显示相关消息。在主类中,定义了模式和文本,并调用了函数。