205. Isomorphic Strings

本文介绍了两种方法来判断两个字符串是否为同构字符串。方法一使用双哈希表确保字符映射的双向唯一性;方法二利用vector记录字符出现的索引,通过比较索引值判断映射关系的一致性。

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.

方法1: two hash

思路:

见了两个hash map, 因为必须保证双向一一对应。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char, char> hash;
        unordered_map<char, char> hash_r;
        for (int i = 0; i < s.size(); i++){
            if (hash.find(s[i]) == hash.end()){
                hash[s[i]] = t[i];
            }
            if (hash_r.find(t[i]) == hash_r.end()){
                hash_r[t[i]] = s[i];
            }
            if (hash[s[i]] != t[i] || hash_r[t[i]] != s[i]){
                return false;
            }
        }
        return true;
    }
};
class Solution{
public:
    bool isIsomorphic(string s, string t) {
        if (s.size() != t.size()) return false;
        vector<int> hash1(256, -1);
        vector<int> hash2(256, -1);
        for (int i = 0; i < s.size(); i++) {
            if (hash1[(int)s[i]] == -1 && hash2[(int)t[i]] == -1) {
                hash1[(int)s[i]] = t[i];
                hash2[(int)t[i]] = s[i];
                continue;
            }
            if (hash1[(int)s[i]] != t[i] || hash2[(int)t[i]] != s[i]) return false;
        }
        return true;
    }
};

方法2:

夏洛的网:https://blog.youkuaiyun.com/liuxiao214/article/details/77587070
思路:

这个方法很巧妙,用两个vector来记录每个字母出现的index。当一对映射出现时,将他们的值都改成两者的坐标。因为初始化都是-1,所以第一次字符对出现都会成功建立坐标。当第二次这对映射再出现(不用管来自哪个字符串),只要他们的坐标相等,表示他们之前也被映射在一起,此时将这对的坐标再次更新。但是当两者不等,如果都不是-1,说明他们上一次并不在同一个映射中出现,如果其中一个不是-1,说明有个字符没出现,另一个已经被映射到了别人。都要返回false。

class Solution104_2 {
public:
    bool isIsomorphic(string s, string t) {
        vector<int>v1(256, -1);
        vector<int>v2(256, -1);
        for (int i = 0; i < s.length();i++)
        {
            if (v1[s[i]] != v2[t[i]])
                return false;
            v1[s[i]] = i;
            v2[t[i]] = i;
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值