Leetcode 205. Isomorphic Strings
205. Isomorphic Strings
Total Accepted: 62899 Total Submissions: 206548 Difficulty: Easy
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.
思路:判断2个字符串是否同构。其实就是映射的问题,如果s和t的字符是一一映射(双射)的关系,就可以说s和t是同构的。
代码:
方法一:将s和t中的字符分别一一映射于整数集合,再对比映射以后的s和t是否相等。
1 class Solution { 2 public: 3 string trans(string s){ 4 int i,m[256]={0}; 5 for(i=0;i<s.size();i++){ 6 if(!m[s[i]]){ 7 m[s[i]]=i+1; 8 } 9 s[i]=m[s[i]]; 10 } 11 return s; 12 } 13 bool isIsomorphic(string s, string t) { 14 if(trans(s)==trans(t)) 15 return true; 16 return false; 17 } 18 };
方法二:
看是否能将s转换为t:
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 char m['z'+1]={0}; 5 bool b['z'+1]={false}; 6 int i; 7 for(i=0;i<s.size();i++){ 8 if(!m[s[i]]&&!b[t[i]]){ 9 m[s[i]]=t[i]; 10 b[t[i]]=true; 11 } 12 if(m[s[i]]==t[i]){ 13 continue; 14 } 15 return false; 16 } 17 return true; 18 } 19 };
方法三:看当前字符最近一次出现的位置是否相等。
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 int m1[256] = {0}, m2[256] = {0}, n = s.size(); 5 for (int i = 0; i < n; ++i) { 6 if (m1[s[i]] != m2[t[i]]) return false; 7 //因为初始值为0,所以要i+1 8 m1[s[i]] = i + 1; //m1记录s[i]在s中最近一次出现的位置 9 m2[t[i]] = i + 1; 10 } 11 return true; 12 } 13 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端