LeetCode -- Isomorphic Strings
2015-09-05 17:10
405 查看
题目描述:
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; } }
相关文章推荐
- C++模板学习之单链表的实现
- 考虑用赋值运算符(op=)取代其单独形式(op)(More Effective C++_22(效率))
- 1.3 git和github -3 同步到远程仓库
- 欢迎使用CSDN-markdown编辑器
- C#做出验证码的例子
- Web开发为什么要使用Struts2和Spring这样的框架?
- leetcode 275: H-Index II
- LoRa无线通信设计(三)小区环境测试
- 内部类
- Leetcode|Sliding Window Maximum(multiset,优先队列,双端队列和区间树的应用)
- 数据库垂直拆分,水平拆分利器,cobar升级版mycat - freewebsys的专栏 - 博客频道 - CSDN.NET
- LISP记录
- eclipse启动闪退总结
- 数据库备份恢复时出现“无法处理,因为正由此会话使用”
- SqlHelper类
- c++primer之顺序容器(添加元素)
- flash乱码解决方案
- nginx 直接在配置文章中设置日志分割
- 源代码搭建LNMP环境
- 源代码搭建LNMP环境