原题
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.
代码实现
public bool IsIsomorphic(string s, string t)
{
var dict = new Dictionary<char, char>(); //s.char->t.char
var dict2 = new Dictionary<char, char>(); //t.char->s.char
for (int i = 0; i < s.Length; i++)
{
if (dict.ContainsKey(s[i]) && dict[s[i]] != t[i] ||
dict2.ContainsKey(t[i]) && dict2[t[i]] != s[i])
return false;
dict[s[i]] = t[i];
dict2[t[i]] = s[i];
}
return true;
}
leetcode-solution库
leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp