Leetcode 205. Isomorphic Strings

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.

For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.

思路:分别存储s到t和t到s的字符映射,然后分别用映射生成对应的映射字符串,最后比较两个映射字符串是否与t和s相同。

public boolean isIsomorphic(String s, String t) {
    if (s == null || t == null || s.length() != t.length()) {
        return false;
    }
    //use map to store the relation
    Map<Character, Character> smap = new HashMap<>();
    Map<Character, Character> tmap = new HashMap<>();

    //iterate s to gen a new string according to the map
    StringBuilder ms = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        char sc = s.charAt(i);
        if (smap.containsKey(sc)) {
            ms.append(smap.get(sc));
        } else {
            char tc = t.charAt(i);
            smap.put(sc, tc);
            tmap.put(tc, sc);
            ms.append(tc);
        }
    }
    StringBuilder mt = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        mt.append(tmap.get(t.charAt(i)));
    }

    return ms.toString().equals(t) && mt.toString().equals(s);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容