Anagram Substring Search ( Or Search for all permutations ) | C # program to search all anagrams of a pattern in a text ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of pat [ ] in txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Driver Code
using System ; class GFG { public const int MAX = 256 ; public static bool compare ( char [ ] arr1 , char [ ] arr2 ) { for ( int i = 0 ; i < MAX ; i ++ ) { if ( arr1 [ i ] != arr2 [ i ] ) { return false ; } } return true ; } public static void search ( string pat , string txt ) { int M = pat . Length ; int N = txt . Length ; char [ ] countP = new char [ MAX ] ; char [ ] countTW = new char [ MAX ] ; for ( int i = 0 ; i < M ; i ++ ) { ( countP [ pat [ i ] ] ) ++ ; ( countTW [ txt [ i ] ] ) ++ ; } for ( int i = M ; i < N ; i ++ ) { if ( compare ( countP , countTW ) ) { Console . WriteLine ( " Found ▁ at ▁ Index ▁ " + ( i - M ) ) ; } ( countTW [ txt [ i ] ] ) ++ ; countTW [ txt [ i - M ] ] -- ; } if ( compare ( countP , countTW ) ) { Console . WriteLine ( " Found ▁ at ▁ Index ▁ " + ( N - M ) ) ; } } public static void Main ( string [ ] args ) { string txt = " BACDGABCDA " ; string pat = " ABCD " ; search ( pat , txt ) ; } }