Skip to content

Instantly share code, notes, and snippets.

@zmerrychristmas
Created March 13, 2022 07:20
Show Gist options
  • Save zmerrychristmas/6e347b1090ab976dcdb203fdccd38363 to your computer and use it in GitHub Desktop.
Save zmerrychristmas/6e347b1090ab976dcdb203fdccd38363 to your computer and use it in GitHub Desktop.
Two words are anagrams of one another if their letters can be rearranged to form the other word. Given a string, split it into two contiguous substrings of equal length. Determine the minimum number of characters to change to make the two substrings into anagrams of one another.
#
# Complete the 'anagram' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def anagram(s)
n = s.length
return -1 if n % 2 == 1
n /= 2
a = s[0, n].split('').sort
b = s[n, s.length/2].split('').sort
if a == b
return 0
end
hash_a = Hash.new(0)
hash_b = Hash.new(0)
a.each{|i| hash_a[i] += 1}
b.each{|j| hash_b[j] += 1}
keys = hash_a.keys & hash_b.keys
a1 = hash_a.select{ |k, v| keys.include? k }
b1 = hash_b.select{ |k, v| keys.include? k }
# num1 = a1.values.sum
# num2 = b1.values.sum
# print a, b, hash_a, hash_b , keys , a1, b1,num1, num2, "\n"
total = 0
for i in keys
total += [hash_a[i], hash_b[i]].min
end
return n - total
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment