leetcode Isomorphic Strings

本文介绍了一种判断两个字符串是否为同构字符串的有效方法。通过构建映射表来确保字符串s到t以及t到s的映射关系正确无误。文章详细展示了如何使用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.

 

 

没做出来。

没有非常清楚的理解题目的意思,题目是说,两个字符串同构。我却认为是只要字符串s中哪些字符串一样,t中相同位置的字符串也要一样。

事实上约束更多,讲的是一种映射,就如同egg,e与a映射,g与d映射,那么字符串s中如果再出现e,字符串t中就必须是a。

所以,构建一个map,用上次见过的方法就行了。if(map.find(s[i])==map.end())****else****

不过需要有两次检查,检查s->t的映射t是否满足,还有t->s的映射s是否满足。

 

 

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         map<char,char> model;
 5         int slength=s.length(),tlength=t.length();
 6         if(slength!=tlength) return false;
 7         for(int i=0;i<slength;i++){
 8             if(model.find(s[i])==model.end()) model[s[i]]=t[i];
 9             else if(model[s[i]]!=t[i]) return false;
10         }
11         model.clear();
12         for(int i=0;i<slength;i++){
13             if(model.find(t[i])==model.end()) model[t[i]]=s[i];
14             else if(model[t[i]]!=s[i]) return false;
15         }
16         return true;
17 
18         
19     }
20 };

 

转载于:https://www.cnblogs.com/LUO77/p/5050356.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值