Length of longest prefix anagram which are common in given two strings | Java program for the above approach ; Function to check if two arrays are identical or not ; Iterate over the range [ 0 , SIZE ] ; If frequency any character is not same in both the strings ; Otherwise ; Function to find the maximum length of the required string ; Store the count of characters in string str1 ; Store the count of characters in string str2 ; Stores the maximum length ; Minimum length of str1 and str2 ; Increment the count of characters of str1 [ i ] in freq1 [ ] by one ; Increment the count of characters of str2 [ i ] in freq2 [ ] by one ; Checks if prefixes are anagram or not ; Finally print the ans ; Driver code ; Function Call
public class Main { static int SIZE = 26 ; static boolean longHelper ( int [ ] freq1 , int [ ] freq2 ) { for ( int i = 0 ; i < SIZE ; ++ i ) { if ( freq1 [ i ] != freq2 [ i ] ) { return false ; } } return true ; } static void longCommomPrefixAnagram ( String s1 , String s2 , int n1 , int n2 ) { int [ ] freq1 = new int [ 26 ] ; int [ ] freq2 = new int [ 26 ] ; int ans = 0 ; int mini_len = Math . min ( n1 , n2 ) ; for ( int i = 0 ; i < mini_len ; ++ i ) { freq1 [ s1 . charAt ( i ) - ' a ' ] ++ ; freq2 [ s2 . charAt ( i ) - ' a ' ] ++ ; if ( longHelper ( freq1 , freq2 ) ) { ans = i + 1 ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String str1 = " abaabcdezzwer " ; String str2 = " caaabbttyh " ; int N = str1 . length ( ) ; int M = str2 . length ( ) ; longCommomPrefixAnagram ( str1 , str2 , N , M ) ; } }