[LeetCode]205. Isomorphic Strings 解题报告(C++)

本文解析了LeetCode上205题Isomorphic Strings的解题思路及C++代码实现,介绍了如何通过哈希表来判断两个字符串是否同构,并给出了一种高效的解决方案。

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

[LeetCode]205. Isomorphic Strings 解题报告(C++)

题目描述

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:

  • 判断字符串是否同构. 两个字符串相同位置的字符应该能够互相替换.
  • 由于ASCII码只有256个.用256大小的数组代替哈希表.并初始化为0.
  • 遍历字符串.按索引位置各取出一个字符.若其对应哈希表相同.则更新哈希值为i+1
  • 否则不同就是说二者非同构.
代码实现:
class Solution {
public:
    bool isIsomorphic(string s, string t) {

        int m1[256] = { 0 }, m2[256] = { 0 };
        int 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;
    }
};

小结

  • 方法1:每次更新索引位置上的字符的哈希表.. 太厉害了.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值