LeetCode Isomorphic Strings

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.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

Note:
You may assume both and have the same length.


判断两个字符串是否同构。同构的意思是字符串s和t中的字母能找到一种一一映射的关系,使得通过这个映射之后s能变成t,t也能变成s。 简单题,维护两个hash表,一个保存s到t的映射,另一个保存t到s的映射。在遍历字符串的过程中,同时判断两个映射是否满足一一映射。 注意不能只用一个hash,因为可能出现s=ab,t=aa的情况,看s->t,a映射到a,b映射到b,没有问题。但是看t->s时,有问题,出现了a既映射到a又映射到b的情况。所以需要同时保存s到t和t到s的映射。 代码如下:

class Solution {
public:
    bool isIsomorphic(string s, string t)
    {
        unordered_map<char, char> hash1, hash2;
        for (int i = 0; i < s.size(); ++i) {
            if (hash1.find(s[i]) == hash1.end())
                hash1[s[i]] = t[i];
            else {
                if (hash1[s[i]] != t[i])
                    return false;
            }
            if (hash2.find(t[i]) == hash2.end())
                hash2[t[i]] = s[i];
            else {
                if (hash2[t[i]] != s[i])
                    return false;
            }
        }
        return true;
    }
};

本代码提交AC,用时13MS。

Leave a Reply

Your email address will not be published. Required fields are marked *