Wednesday, February 18, 2015

if two strings are anagrams

isAnagram(s1, s2):
    if s1 == null || s2 == null
        return false
    if s1.length != s2.length
        return false
    result = true
    map1 = map(s1)
    map2 = map(s2)
    foreach c in map1.keys:
        count1 = map1[c]
        count2
        map2.tryGetValue(c, out count2)
        if count1 != count2:
            result = false
            break
    return result

map(s):
    map = new
    foreach c in s:
        count
        if !map.tryGetValue(c, out count):
            count = 0
        map[c] = ++count
    return map
With 1 map only.
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