Check if two strings are k | Java program for the above approach ; Function to check k anagram of two strings ; First Condition : If both the strings have different length , then they cannot form anagram ; Converting str1 to Character Array arr1 ; Converting str2 to Character Array arr2 ; Sort arr1 in increasing order ; Sort arr2 in increasing order ; Iterate till str1 . length ( ) ; Condition if arr1 [ i ] is not equal to arr2 [ i ] then add it to list ; Condition to check if strings for K - anagram or not ; Driver Code ; Function Call
import java . util . * ; class GFG { public static boolean kAnagrams ( String str1 , String str2 , int k ) { int flag = 0 ; List < Character > list = new ArrayList < > ( ) ; if ( str1 . length ( ) != str2 . length ( ) ) System . exit ( 0 ) ; char arr1 [ ] = str1 . toCharArray ( ) ; char arr2 [ ] = str2 . toCharArray ( ) ; Arrays . sort ( arr1 ) ; Arrays . sort ( arr2 ) ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( arr1 [ i ] != arr2 [ i ] ) { list . add ( arr2 [ i ] ) ; } } if ( list . size ( ) <= k ) flag = 1 ; if ( flag == 1 ) return true ; else return false ; } public static void main ( String [ ] args ) { String str1 = " fodr " ; String str2 = " gork " ; int k = 2 ; kAnagrams ( str1 , str2 , k ) ; if ( kAnagrams ( str1 , str2 , k ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }