205. Isomorphic Strings

本文介绍了一种通过编码映射的方式来判断两个字符串是否为同构的方法,并提供了C++实现代码,时间复杂度为O(n),空间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

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.

Note:
You may assume both s and t have the same length.

题目链接:


思路分析

判断连个字符串是否是同构的,两字符串长度相同。也就是把字母换成编码的话,两个字符串的编码是相同的

s-> 编码相同 <- t

因此我们用两个int的vector来表示两个string的编码,一开始都是置-1,因为0是代表着字母的。然后遍历string,将相应的编码置为第一次出现时的位置,然后在循环过程中对比,编码有没有出现错位,完成同构判断。

代码
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        vector<int> smap(256, -1);
        vector<int> tmap(256, -1);
        int n = s.length();
        for (int i = 0; i < n; i++){
            if (smap[s[i]] != tmap[t[i]])
                return false;
            smap[s[i]] = i;
            tmap[t[i]] = i;
        }
        return true;
    }
};

时间复杂度: O(n)
空间复杂度: O(n)


反思

遇到了很大的阻力,没有想明白这道题目的思路。看过博客之后才明白了用数字代替string中字母的方式,然后就可以对字符相应位置的编码是否相同进行判断了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值