Interview 150

Isomorphic Strings

Problem
LC 205
File
interview150_LC205IsomorphicStrings.java
Path
pkg5leetcode/interview150/interview150_LC205IsomorphicStrings.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC205IsomorphicStrings.java
Lesson
Back to the chapter
Approach
Two hash maps enforce one-to-one char mapping.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC205IsomorphicStrings.java
1package pkg5leetcode.interview150;2 3/*4 * Isomorphic Strings | LC 2055 * APPROACH: Two hash maps enforce one-to-one char mapping.6 * COMPLEXITY: Time O(n), Space O(1)7 */8import java.util.*;9 10public class interview150_LC205IsomorphicStrings {11    static boolean isIsomorphic(String s, String t) {12        if (s.length() != t.length()) return false;13        Map<Character, Character> st = new HashMap<>();14        Map<Character, Character> ts = new HashMap<>();15        for (int i = 0; i < s.length(); i++) {16            char a = s.charAt(i), b = t.charAt(i);17            if (st.containsKey(a) && st.get(a) != b) return false;18            if (ts.containsKey(b) && ts.get(b) != a) return false;19            st.put(a, b);20            ts.put(b, a);21        }22        return true;23    }24 25    public static void main(String[] args) {26        check(isIsomorphic("egg", "add"), "case1");27        check(!isIsomorphic("foo", "bar"), "case2");28        System.out.println("all tests passed");29    }30 31    static void check(boolean cond, String name) {32        if (!cond) throw new AssertionError("FAILED: " + name);33        System.out.println("  PASS " + name);34    }35}