Strings Homomorphism

来源:互联网 发布:淘宝买汽车配件 编辑:程序博客网 时间:2024/05/30 02:25

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.

 注意事项

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

样例

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

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

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

题意: 给两个字符串s和t,看他们是否是同构的,如果s中的字符能被t中的字符替换,所有字符的出现都必须用另一个字符替换,同时保留字符的顺序,没有两个字符可以映射到同一个字符,但字符可以映射到自己。


思路: 利用map

private Map<Character, Character> map = new HashMap<>();    /**     * @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) {        if (s.length() != t.length()) return false;        map.clear();        boolean isIsomorphic = true;        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            Object o = map.get(c);            if (o == null) {                if (findKeyInMap(t.charAt(i))) {                    isIsomorphic = false;                    break;                } else {                    map.put(c, t.charAt(i));                }            } else if (((Character) o).charValue() != t.charAt(i)) {                isIsomorphic = false;                break;            }        }        return isIsomorphic;    }    private boolean findKeyInMap(char c) {        return map.containsValue(c);    }


原创粉丝点击