LeetCode -- Isomorphic Strings
Description:
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.
Returns the homogeneous string. That is, the new string obtained after each character is replaced by the same character and the length of the two strings is the same. Such a string is a homogeneous string.
Ideas:
Returns false if the length is not equal.
Two hash tables, hash1 and has2. Hash1: record the position of the last occurrence of the current character while traversing the first string.
If hash1 contains s [I], then hash2 must also contain t [I] And hash1 [s [I] (s [I] the last position where it appears) it must also be equal to the last position where hash2 [t [I] (t [I] appears ).
If hash1 does not contain s [I], then hash2 must not contain t [I].
Implementation Code:
public class Solution { public bool IsIsomorphic(string s, string t) { var hash1 = new Dictionary
();var hash2 = new Dictionary
();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; }}