Check if two strings are k | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool kAnagrams ( string str1 , string str2 , int k ) { int flag = 0 ; if ( str1 . length ( ) != str2 . length ( ) ) return false ; int n = str1 . length ( ) ; char arr1 [ n ] ; char arr2 [ n ] ; strcpy ( arr1 , str1 . c_str ( ) ) ; strcpy ( arr2 , str2 . c_str ( ) ) ; sort ( arr1 , arr1 + n ) ; sort ( arr2 , arr2 + n ) ; vector < char > list ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( arr1 [ i ] != arr2 [ i ] ) { list . push_back ( arr2 [ i ] ) ; } } if ( list . size ( ) <= k ) flag = 1 ; if ( flag == 1 ) return true ; else return false ; } int main ( ) { string str1 = " anagram " , str2 = " grammar " ; int k = 3 ; kAnagrams ( str1 , str2 , k ) ; if ( kAnagrams ( str1 , str2 , k ) == true ) cout << " Yes " ; else cout << " No " ; }