205. Isomorphic Strings

Given two stringssandt, determine if they are isomorphic.

Two strings 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.

For example,
Given"egg","add", return true.

Given"foo","bar", return false.

Given"paper","title", return true.

Note:
You may assume both s and t have the same length.

Analysis

创建一个256长度的array, 包含所有ASCII character. 每个s中的字母对应的int里放t中字母对应的int. 用set记录放进array中的t int value, 以防止 s="ab" t="aa"这种s中a和b都对应同样字母都问题;

My Solution:

public boolean isIsomorphic(String s, String t) {
    if (s == null || t == null || s.length() != t.length()) {
        return false;
    }
    int[] idxMap = new int[256];
    Set<Integer> set= new HashSet<>();
    for (int i = 0; i < s.length(); ++i) {
        int si = (int) (s.charAt(i));
        int ti = (int) (t.charAt(i));
        if (idxMap[si] == 0) {
            if (set.contains(ti)) {
                return false;
            }
            idxMap[si] = ti;
            set.add(ti);
        } else if (idxMap[si] != ti) {
            return false;
        }
    }
    return true;
}

Solution without Map or Set

public boolean isIsomorphic (String s, String t) {
    int[] m1 = new int[256];
    int[] m2 = new int[256];
    int n = s.length();
    for (int i = 0; i < n; i++) {
        if (m1[s.charAt(i)] != m2[t.charAt(i)]) {
            return false;
        }
        m1[s.charAt(i)] = i + 1;
        m2[t.charAt(i)] = i + 1;
    }
    return true;
}

results matching ""

    No results matching ""