arcbjorn

thoughtbook

RSS Feed

Sunday, December 18, 2022

Isomorphic strings

Leetcode 205 problem.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Go

  • Time complexity: O(n)O(n) - n is a length of a string (assuming both strings are the same length)
  • Auxiliary space: O(n)O(n) - n is a length of a string (assuming both strings are the same length)
func isIsomorphic(s string, t string) bool {
    charCodes1 := make([]int, 256)
    charCodes2 := make([]int, 256)

    for i := 0; i < len(s); i++ {
        if charCodes1[int(s[i])] != charCodes2[int(t[i])] {
            return false
        }

        nextCharIdx := i + 1
        charCodes1[int(s[i])] = nextCharIdx
        charCodes2[int(t[i])] = nextCharIdx
    }

    return true
}
Creative Commons Licence