205.同构字符串

题目来源:力扣icon-default.png?t=M85Bhttps://leetcode.cn/problems/isomorphic-strings/

题目简介:

给定一个特定的同构关系,判断两个字符串s和t是不是同构关系,比较关键的就是一个字母只能映射一种字母,不能一对多,也不能多对一

思路:

设置两张哈希表,保证双向字符对应一致,一张用s里的字符做key,t里的字符做值,另一张用t里的字符做key,s里的字符做值。从左至右遍历两个字符串的字符,不断更新两张哈希表,如果出现冲突(即当前下标对应的字符 s[index] 已经存在映射且不为t[index] 或当前下标对应的字符 t[index] 已经存在映射且不为 s[index])时说明两个字符串无法构成同构,返回 false。 如果遍历结束没有出现冲突,两个字符串是同构的,返回true

代码实现:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map s2t;
        unordered_map t2s;
        int len = s.length();
        for (int i = 0; i < len; ++i) {
            char x = s[i], y = t[i];
            if ((s2t.count(x) && s2t[x] != y) || (t2s.count(y) && t2s[y] != x)) {
                return false;
            }
            s2t[x] = y;
            t2s[y] = x;
        }
        return true;
    }
};

你可能感兴趣的:(leetcode专栏,leetcode,算法,职场和发展)