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 s and t have the same length.


这道题可以使用一个哈希表来存储已遍历的配对,用一个集合来保存被配对的字符,如果出现字符串s和t中相应的字符对不在哈希表中或者被配对的字符在集合中已经出现过,则认为这两个字符串不是同构字符串。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len1 = s.size();
        int len2 = t.size();
        if(len1 != len2)
            return false;
        unordered_map<int, int> characterMap;
        set<int> data;
        for(int i=0;i<len1;i++){
            if(characterMap.find(s[i]) != characterMap.end()){
                if(characterMap[s[i]] != t[i])
                    return false;
            }
            else{
                if(data.find(t[i]) != data.end())
                    return false;
                characterMap[s[i]] = t[i];
                data.insert(t[i]);
            }
        }
        return true;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容