Leetcode 75: Day 2: 205. Isomorphic Strings

Question:

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.

Solution:

  • Maintain a HashMap to store the mapping of characters.
  • If the ith character of s string is not present in HashMap (mapping is not present), then add its corresponding mapping to the HashMap.
  • But before adding the mapping, check if there is any other character already having the mapped value as the ith character of t string.
  • If the mapping already exists for that value, return false. Else, add the mapping.
  • If a mapping for a character already exists, then check if the mapped character equals the ith character in t-string. If not, return false. Else, continue.
  • Return true once all the indices have been analyzed.

Code:


class Solution {
    public boolean isIsomorphic(String s, String t) {

        HashMap<Character, Character> mapping = new HashMap<>();

        for(int i = 0; i < s.length(); i++){

            if(mapping.containsKey(s.charAt(i))){

                if(mapping.get(s.charAt(i)) != t.charAt(i)) return false;

            } else{

                if(mapping.containsValue(t.charAt(i))) return false;
                mapping.put(s.charAt(i), t.charAt(i));

            }      

        }

        return true;

    }
}

Complexity:

  • Time: O(N)
  • Time: O(N)