Given two String s and t, determine if they are isomorphic
Two strings are isomorphic if the characters in s can be replaced to get t .
All occurences of a character must be replaced with anther character while preserving the order of characters . Now 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;
提示:使用Hash表
Hash Table
翻译:
给定两个字符串s和t,确定它们是否同构
如果字符可以被替换,则两个字符串是同构,
所有出现的字符必须与另一个字符更换,同时保留字符的顺序。现在两个字符可能映射到相同的字符,但是一个字符可能映射到其本身
结题思路:用哈希表表示映射关系。第一遍,用S的每个char作为key,映射的t的char作为value,如果出现一个不匹配,则返回为false;第二遍,用t的每个char作为key,映射的s的char作为value,同样,如果一旦出现不匹配或者多个映射,则返回false;直到程序最后都没有返回值,则说明两个串同构,返回true;
public static boolean isIsomorphic1(String s,String t)
{
if(s==null||t==null)
return false;
if(s.length()!=t.length())
return false;
HashMap<Character, Character> ht1=new HashMap<Character, Character>();
HashMap<Character, Character> ht2=new HashMap<Character, Character>();
for (int i = 0; i < s.length(); i++)
{
char sourceChar=s.charAt(i);
char targetChar=t.charAt(i);
if(!ht1.containsKey(sourceChar))
{
ht1.put(sourceChar, targetChar);
}
else
{
if(!ht1.get(sourceChar).equals(targetChar))
{
return false;
}
}
}
for (int i = 0; i < t.length(); i++)
{
char targetChar=s.charAt(i);
char sourceChar=t.charAt(i);
if(!ht2.containsKey(sourceChar))
{
ht2.put(sourceChar, targetChar);
}
else
{
if(!ht2.get(sourceChar).equals(targetChar))
{
return false;
}
}
}
return true;
}