[leetcode] 205. Isomorphic Strings

Description

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.

分析一

题目的意思是:判断两个字符串是否是同构的。

  • 用两个hash表来建立两字符串字符的映射,如果出现一对多的映射,说明就不是同构的。

代码一

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char,char> res,st;
        for(int i=0;i<s.length();i++){
            if(res.count(s[i])||st.count(t[i])){
                if(res[s[i]]!=t[i]||st[t[i]]!=s[i]){
                    return false;
                }
            }else{
                res[s[i]]=t[i];
                st[t[i]]=s[i];
            }
        }
        return true;
    }
};

分析二

  • 两个哈希表分别来记录原字符串和目标字符串中字符出现情况,由于ASCII码只有256个字符,所以我们可以用一个256大小的数组来代替哈希表,并初始化为0;
  • 我们遍历原字符串,分别从源字符串和目标字符串取出一个字符,然后分别在两个哈希表中查找其值,若不相等,则返回false,若相等,将其值更新为i + 1,因为默认的值是0,所以我们更新值为i + 1,这样当 i=0 时,则映射为1,如果不加1的话,那么就无法区分是否更新了。

代码二

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int m1[256] = {0}, m2[256] = {0}, n = s.size();
        for (int i = 0; i < n; ++i) {
            if (m1[s[i]] != m2[t[i]]) return false;
            m1[s[i]] = i + 1;
            m2[t[i]] = i + 1;
        }
        return true;
    }
};

Python实现

用两个字典进行模拟即可:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        st = dict()
        ts = dict()
        for s1,t1 in zip(s,t):
            if s1 not in st:
                st[s1]=t1
            if t1 not in ts:
                ts[t1]=s1
            if st[s1]!=t1 or ts[t1]!=s1:
                return False
        return True

参考文献

[LeetCode] Isomorphic Strings 同构字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值