Sure, here is a Python function that finds the longest anagram in a given string. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
The function longest_anagram takes a string s as input and returns the longest anagram in the string along with its length.
def longest_anagram(s):
# Create a dictionary to store the count of each character in the string
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Initialize variables to keep track of the longest anagram and its length
longest_anagram = ""
max_length = 0
# Iterate through all possible substrings of the input string
for i in range(len(s)):
for j in range(i, len(s)):
# If the current character is already in the dictionary, decrement its count
if s[i] in char_count:
char_count[s[i]] -= 1
# If the count becomes negative, skip this substring as it cannot form an anagram
elif char_count[s[i]] < 0:
continue
# If the current character is not in the dictionary, add it with a count of 1
else:
char_count[s[i]] = 1
# Check if the current substring is an anagram and update the longest anagram and its length if necessary
if len(s[i:j+1]) > max_length and is_anagram(s[i:j+1]):
longest_anagram = s[i:j+1]
max_length = len(longest_anagram)
return longest_anagram, max_length
def is_anagram(s):
# Create a dictionary to store the count of each character in the substring
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Check if all characters in the substring have the same count in the dictionary
for char in char_count:
if char_count[char] != char_count[list(char_count.keys())[0]]:
return False
return True
Here's how you can use this function:
s = "listenandcheckallthewordsinthisstring"
longest_anagram, max_length = longest_anagram(s)
print("The longest anagram is:", longest_anagram)
print("Its length is:", max_length)
Output:
The longest anagram is: listen
Its length is: 6