Isomorphic Strings

Isomorphic Strings

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.

LeetCode Problem - 205

class Solution {
    public boolean isIsomorphic(String s, String t) {
        // Map to store character mappings from string s to string t
        Map<Character, Character> map = new HashMap<>();

        // If lengths of both strings are different, they can't be isomorphic
        if (s.length() != t.length()) return false;

        // Iterate through each character in string s
        for (int i = 0; i < s.length(); i++) {
            // If the current character in s is not mapped and the corresponding character in t is not mapped, map them
            if (!map.containsKey(s.charAt(i)) && !map.containsValue(t.charAt(i))) {
                map.put(s.charAt(i), t.charAt(i));
            }
        }

        // Try to verify if string s and t are isomorphic
        try {
            // Iterate through each character in string s
            for (int i = 0; i < s.length(); i++) {
                // Get the mapped value for the current character in s
                char value = map.get(s.charAt(i));
                // If the mapped value doesn't match the corresponding character in t, they are not isomorphic
                if (value != t.charAt(i)) return false;
            }
        } 
        // If an exception occurs, it means that the characters are not correctly mapped
        catch (Exception e) {
            return false;
        }

        // If the above conditions are passed, strings s and t are isomorphic
        return true;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!