LeetCode:Isomorphic Strings

本文介绍了一种算法,用于判断两个字符串是否为同构字符串。通过使用两个字符映射表,确保了字符之间的正确对应关系,并提供了C++实现代码。

摘要生成于 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.

Subscribe to see which companies asked this question

思路:

这道题是判断两个单词是否同构。这里的同构的意思是,对于例子egg和add,若存在一个映射,e->a,g->d,单词egg和add同构。注意,不可以多个字符映射到同一个字符中去,比如aa和ab。因此要有两个hash表来记录。由于是字符,不会超过256个,因此可以用数组来记录这种映射。

代码:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.length() != t.length())  return false;
        char charmap1[256];
        char charmap2[256];
        memset(charmap1,0,sizeof(char) * 256);
        memset(charmap2,0,sizeof(char) * 256);

        for(int i = 0; i < s.length();++i){
            if(charmap1[s[i]] == 0){
                charmap1[s[i]] = t[i] ;
            }
            else if(charmap1[s[i]] != t[i]){
                return  false;
            }
             if(charmap2[t[i]] == 0){
                charmap2[t[i]] = s[i] ;
            }
            else if(charmap2[t[i]] != s[i]){
                return  false;
            }
        }
       return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

fullstack_lth

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

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

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

打赏作者

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

抵扣说明:

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

余额充值