题目:
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.
题意:
就是给定两个字符串,判断这两个字符串的结构是否是一样的。那么这道题和之前有一道给定一个pattern,然后判断输入的字符串是否符合pattern的那个模式。当时那个题是采用一个map + set来做,就是首先用一个map来一一对应pattern和字符串的字符,当出现重复的pattern时,查看字符串的字符是否与之前出现的一致。那么联想到可以采用map来一一对应的做,此题我就考虑了也用map来做,通过将两个字符串中的每一个对应位置上的字符用map一一对应的存,然后当出现重复的时候,再判断是否是曾经出现过的,如果是曾经出现过的,那么就是true,否则就是false;但是有一种情况要当心,也就是如果输入的是ab,那么第二个字符串如果是aa,就还得考虑第二个字符是不是与之前的字符一致,如果一致,那么也返回false。
public static boolean isIsomorphic(String s, String t)
{
Map<Character,Character> map = new HashMap<Character,Character>();
int length = s.length();
for(int i = 0; i < length; i++)
{
if(!map.containsKey(s.charAt(i)) && !map.containsValue(t.charAt(i)))
{
map.put(s.charAt(i), t.charAt(i));
//System.out.println(s.charAt(i) + " " + map.get(s.charAt(i)));
}
else if(!map.containsKey(s.charAt(i)) && map.containsValue(t.charAt(i))) //这种情况是针对,ab ,aa那么就是返回false
return false;
else if(map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) != t.charAt(i))
return false;
}
return true;
}