DEV Community

Cover image for 205. Isomorphic Strings
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on • Updated on

205. Isomorphic Strings

205. Isomorphic Strings

Easy

Given two strings s and t, determine if they are isomorphic.

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.

Example 1:

  • Input: s = "egg", t = "add"
  • Output: true

Example 2:

  • Input: s = "foo", t = "bar"
  • Output: false

Example 3:

  • Input: s = "paper", t = "title"
  • Output: true

Constraints:

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s and t consist of any valid ascii character.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Solution:

class Solution {

    /**
     * @param String $s
     * @param String $t
     * @return Boolean
     */
    function isIsomorphic($s, $t) {        
        $last_seen_s = array_fill(0, 256, 0);
        $last_seen_t = array_fill(0, 256, 0);

        foreach (array_map(null, str_split($s), str_split($t)) as $index => [$char_s, $char_t]) {
            $index += 1;
            $ascii_s = ord($char_s);
            $ascii_t = ord($char_t);

            if ($last_seen_s[$ascii_s] != $last_seen_t[$ascii_t]) {
                return false;
            }

            $last_seen_s[$ascii_s] = $last_seen_t[$ascii_t] = $index;
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Contact Links

Top comments (0)