Problem

Given two strings s and t, 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.

Notice

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

Example

Given s = "egg", t = "add", return true.

Given s = "foo", t = "bar", return false.

Given s = "paper", t = "title", return true.

Solution

public class Solution {
    /*
     * @param s: a string
     * @param t: a string
     * @return: true if the characters in s can be replaced to get t or false
     */
    public boolean isIsomorphic(String s, String t) {
        //Map<Integer, Integer> => (k, v) = (frequency, amount of chars)
        int[] map_S = new int[256];
        int[] map_T = new int[256];
        if (s == null || t == null || s.length() != t.length()) return false;
        for (int i = 0; i < s.length(); i++) {
            map_S[(int)s.charAt(i)]++; 
            map_T[(int)t.charAt(i)]++;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < 256; i++) {
            if (!map.containsKey(map_S[i])) map.put(map_S[i], 1);
            else map.put(map_S[i], map.get(map_S[i])+1);
        }
        for (int i = 0; i < 256; i++) {
            if (!map.containsKey(map_T[i])) return false;
            else map.put(map_T[i], map.get(map_T[i])-1);
            if (map.get(map_T[i]) < 0) return false;
        }
        return true;
    }
}

linspiration
161 声望53 粉丝