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]。


实现代码:





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
原创粉丝点击