Wednesday, February 18, 2015

if two strings are anagrams

bool isAnagram(s1, s2):
    if s1 == null || s2 == null
        return false
    if s1.length() != s2.length()
        return false
    map1 = map(s1)
    map2 = map(s2)
    if map1.keys.count() != map2.keys.count():
        return false
    for c in map1.keys():
        if !map2.hasKey(c) || map1[c] != map2[c]:
            return false
    return true

map map(s):
    map = new
    for c in s:
        if map.hasKey(c):
            count = map[c]
        map[c] = count +1
    return map
With 1 map only.
bool isAnagram(s1, s2):
    if s1 == null || s2 == null
        return false
    if s1.length != s2.length
        return false
    result = true
    map = map(s1)
    foreach c in s2:
        if !map.containskey(c) || --map[c] < 0:
            result = false
            break
    return result

[Hat tip to JS]

No comments:

Post a Comment