Strings Homomorphism

http://www.lintcode.com/zh-cn/problem/strings-homomorphism/

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) {
        // write your code here
        if (s == null || t == null) {
            return s == t;
        }
        if (s.length() != t.length()) {
            return false;
        }
//        可以把s当成原文,t当成密文,来维护一个map是密码表,要求它们一一对应
        HashMap map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char src = s.charAt(i);
            char dest = t.charAt(i);
            if (map.containsKey(src)) {
                if (dest != map.get(src)) {
                    return false;
                }
            } else {
                //密文也不能重复,
                if (map.containsValue(dest)) {
                    return false;
                }
                map.put(src, dest);
            }
        }
        return true;
    }
}

你可能感兴趣的:(Strings Homomorphism)