Saturday, June 18, 2016

if two strings are isomorphic

// example
add
egg

adx    false
egg

paper
title

is
so

is
si
is-isomorphic(s1, s2):
    if s1 == null || s2 == null
        || s1.length() != s2.length():
        return false
    if s1 == s2:
        return true
    result = true
    map1to2, map2to1 = new
    for i = 0, i < s1.length(), i++:
        c1 = s1[i], c2 = s2[i]
        if map1to2.has(c1) && map2to1.has(c2):
            if map1to2[c1] != c2 || map2to1[c2] != c1:
                result = false
                break
        else if !map1to2.has(c1) && !map2to1.has(c2):
            map1to2[c1] = c2
            map2to1[c2] = c1
        else:
            result = false
            break
    return result
[Hat tip to SM]

No comments:

Post a Comment