题目链接: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.

这道题的要求是判断两个字符串是否是同构的。

可以采用两个Hash表记录映射的字符。

时间复杂度:O(n)

空间复杂度:O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution
{
public:
    bool isIsomorphic(string s, string t)
    {
        unordered_map<char, char> mst, mts;
        for(int i = 0; i < s.size(); ++ i)
        {
            if(mst.find(s[i]) == mst.end())
                mst[s[i]] = t[i];
            else if(mst[s[i]] != t[i])
                return false;
            
            if(mts.find(t[i]) == mts.end())
                mts[t[i]] = s[i];
            else if(mts[t[i]] != s[i])
                return false;
        }
        return true;
    }
};

当然也可以用Hash表映射字符在字符串中的索引。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution
{
public:
    bool isIsomorphic(string s, string t)
    {
        unordered_map<char, int> ms, mt;
        for(int i = 0; i < s.size(); ++ i)
        {
            if(ms[s[i]] != mt[t[i]])
                return false;
            ms[s[i]] = mt[t[i]] = i + 1;
        }
        return true;
    }
};