【leetcode】Isomorphic Strings(easy)

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.

 

秒小题好爽的说。

思路:保存两个字符串字母对应的字母,出现不一致就false

我的代码:

bool isIsomorphic(string s, string t) { 

        unordered_map<char, char> map1, map2;

        for(int i = 0; i < s.size(); ++i)

        {

            if(map1.find(s[i]) == map1.end() && map2.find(t[i]) == map2.end())

            {

                map1[s[i]] = t[i]; map2[t[i]] = s[i];

            }

            else if(map1[s[i]] != t[i] || map2[t[i]] != s[i])

                return false;

            else;

        }

        return true;

    }

网上C版本代码 免去了查找 更快

bool isIsomorphic(char* s, char* t) {

        char mapST[128] = { 0 };

        char mapTS[128] = { 0 };

        size_t len = strlen(s);

        for (int i = 0; i < len; ++i)

        {

            if (mapST[s[i]] == 0 && mapTS[t[i]] == 0)

            {

                mapST[s[i]] = t[i];

                mapTS[t[i]] = s[i];

            }

            else

            {

                if (mapST[s[i]] != t[i] || mapTS[t[i]] != s[i])

                    return false;

            }

        }

        return true;    

}

 

你可能感兴趣的:(LeetCode)