Check if a string contains an anagram of another string as its substring | Function to check if string s2 contains anagram of the string s1 as its substring ; Stores frequencies of characters in substrings of s2 ; Stores frequencies of characters in s1 ; If length of s2 exceeds length of s1 ; Store frequencies of characters in first substring of length s1len in string s2 ; Perform Sliding Window technique ; If hashmaps are found to be identical for any substring ; Driver Code
def checkAnagram ( s1 , s2 ) : NEW_LINE INDENT s2hash = [ 0 for i in range ( 26 ) ] NEW_LINE s1hash = [ 0 for i in range ( 26 ) ] NEW_LINE s1len = len ( s1 ) NEW_LINE s2len = len ( s2 ) NEW_LINE if ( s1len > s2len ) : NEW_LINE INDENT return False NEW_LINE DEDENT left = 0 NEW_LINE right = 0 NEW_LINE while ( right < s1len ) : NEW_LINE INDENT s1hash [ ord ( s1 [ right ] ) - 97 ] += 1 NEW_LINE s2hash [ ord ( s2 [ right ] ) - 97 ] += 1 NEW_LINE right += 1 NEW_LINE DEDENT right -= 1 NEW_LINE while ( right < s2len ) : NEW_LINE INDENT if ( s1hash == s2hash ) : NEW_LINE INDENT return True NEW_LINE DEDENT right += 1 NEW_LINE if ( right != s2len ) : NEW_LINE INDENT s2hash [ ord ( s2 [ right ] ) - 97 ] += 1 NEW_LINE DEDENT s2hash [ ord ( s2 [ left ] ) - 97 ] -= 1 NEW_LINE left += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " ab " NEW_LINE s2 = " bbpobac " NEW_LINE if ( checkAnagram ( s1 , s2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT