LeetCode -- Isomorphic Strings
来源:互联网 发布:蛐蛐钢琴软件 编辑:程序博客网 时间:2024/05/17 08:36
题目描述:
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.
判断同构字符串。 就是两个字符串长度相同,并且每一位被相同的字符替代后所得的新字符串相等,这样的字符串是同构字符串。
思路:
长度不等直接返回false。
两个哈希表hash1 和has2。 hash1 : 遍历第一个字符串的同时,记录当前字符最后一次出现的位置。
如果hash1中包含了s[i],那么hash2也一定要包含t[i]并且hash1[s[i]](s[i]最后一次出现的位置)也要等于hash2[t[i]](t[i]最后一次出现的位置)。
如果hash1中没有包含s[i],那么hash2也一定不能包含t[i]。
实现代码:
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.
判断同构字符串。 就是两个字符串长度相同,并且每一位被相同的字符替代后所得的新字符串相等,这样的字符串是同构字符串。
思路:
长度不等直接返回false。
两个哈希表hash1 和has2。 hash1 : 遍历第一个字符串的同时,记录当前字符最后一次出现的位置。
如果hash1中包含了s[i],那么hash2也一定要包含t[i]并且hash1[s[i]](s[i]最后一次出现的位置)也要等于hash2[t[i]](t[i]最后一次出现的位置)。
如果hash1中没有包含s[i],那么hash2也一定不能包含t[i]。
实现代码:
public class Solution { public bool IsIsomorphic(string s, string t) { var hash1 = new Dictionary<char, int>();var hash2 = new Dictionary<char, int>();for(var i = 0;i < s.Length; i++){if(!hash1.ContainsKey(s[i])){hash1.Add(s[i], i);if(hash2.ContainsKey(t[i])){return false;}hash2.Add(t[i],i);}else{if(!hash2.ContainsKey(t[i]) || hash2[t[i]] != hash1[s[i]]){return false;}hash1[s[i]] = i;hash2[t[i]] = i;}}return true; }}
0 1
- LeetCode 205 - Isomorphic Strings
- [LeetCode] Isomorphic Strings
- Isomorphic Strings Leetcode JAVA
- [LeetCode] Isomorphic Strings
- [LeetCode 205]Isomorphic Strings
- LeetCode 205-Isomorphic Strings
- leetcode Isomorphic Strings
- leetcode(c++) Isomorphic Strings
- leetcode--Isomorphic Strings
- [LeetCode]Isomorphic Strings
- LeetCode OJ Isomorphic Strings
- leetcode 205: Isomorphic Strings
- leetcode 205 Isomorphic Strings
- [leetcode] Isomorphic Strings
- 【leetcode】Isomorphic Strings
- [leetcode]Isomorphic Strings
- [LeetCode]Isomorphic Strings
- leetcode--Isomorphic Strings
- 欢迎使用CSDN-markdown编辑器
- Java线程:线程栈模型与线程的变量
- MapReduce 的工作机制
- Web开发为什么要使用Struts2和Spring这样的框架?
- c#文件读入读出笔记
- LeetCode -- Isomorphic Strings
- 考虑用赋值运算符(op=)取代其单独形式(op)(More Effective C++_22(效率))
- 页面之间的卷滚切换效果
- windows下安装python第三方库
- mysql数据库用source命令导入.sql文件,执行SQL语句
- 话说验证码识别
- 在IB中使用Auto Layout来添加UIScrollView
- java 动态代理
- java多线程相关基础