我们如何创建一个程序来检查我们给出的输入(例如:EXAMPLE)是否与(XAMPLEE)具有相同的长度和相同的字母?
答案 0 :(得分:0)
这是它的高效python代码
NO_OF_CHARS = 256
def areAnagram(str1, str2):
# Create two count arrays and initialize all values as 0
count1 = [0] * NO_OF_CHARS
count2 = [0] * NO_OF_CHARS
# For each character in input strings, increment count
# in the corresponding count array
for i in str1:
count1[ord(i)]+=1
for i in str2:
count2[ord(i)]+=1
# If both strings are of different length. Removing this
# condition will make the program fail for strings like
# "aaca" and "aca"
if len(str1) != len(str2):
return 0
# Compare count arrays
for i in xrange(NO_OF_CHARS):
if count1[i] != count2[i]:
return 0
return 1
str1 = "EXAMPLE"
str2 = "XAMPLEE"
if areAnagram(str1, str2):
print "The two strings are anagram of each other"
else:
print "The two strings are not anagram of each other"
答案 1 :(得分:0)
import array
word1 = "EXAMPLE"
word2 = "XAMPLEE"
letters = array.array('i',(0,)*26)
# Count letters of word1
for c in word1:
charIndex = ord(c) - ord('A')
letters[charIndex] = letters[charIndex]+1
# Count letters of word2 and substract them from word1 count
for c in word2:
charIndex = ord(c) - ord('A')
letters[charIndex] = letters[charIndex]-1
# letters contains only 0 if words are the same
if letters.count(0) < 26:
print("Words are different")
else:
print("Words are anagrams")