Leetcode P0205"Isomorphic Strings" 题解

2020/10/13 Leetcode

博文中会简要介绍Leetcode P0205题目分析及解题思路。

“Isomorphic Strings”是一道比较简单的题目,我们可以利用两个HashTable来建立字符串s和字符串t之间的一对一特异性的映射关系。所谓“特异性”表示s中的字符只能有唯一的t中的一个字符来替换,反之同理。

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.

以下是Java的题解代码实现。

class Solution {
    public boolean isIsomorphic(String s, String t) {
        int L1 = s.length(), L2 = t.length();
        if (L1 != L2) 
            return false;
        
        Map<Character, Character> s2tMap = new HashMap<>();
        Map<Character, Character> t2sMap = new HashMap<>();
        for (int idx=0; idx<L1; ++idx) {
            char sch = s.charAt(idx), tch = t.charAt(idx);
            if (!s2tMap.containsKey(sch)) {
                if (t2sMap.getOrDefault(tch, sch) != sch)
                    return false;
                
                t2sMap.put(tch, sch);
                s2tMap.put(sch, tch);
            }
            else {
                if (s2tMap.get(sch) != tch)
                    return false;
            }
        }
        
        return true;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int L1 = s.length(), L2 = t.length();
        if (L1 != L2)
            return false;
        
        unordered_map<char, char> s2t, t2s;
        for (int idx=0; idx<L1; ++idx) {
            char tch = t[idx], sch = s[idx];
            if (s2t.count(sch) == 0) {
                if (t2s.count(tch) > 0 && t2s[tch] != sch)
                    return false;
                
                s2t[sch] = tch;
                t2s[tch] = sch;
            }
            else {
                if (s2t[sch] != tch)
                    return false;
            }
        }
        
        return true;
    }
};

Search

    Table of Contents