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.
方法一:用一个转换函数,将我们现在的字符串弄成0123…替代的字符串,比如abcca为01220,最后比较转换出来的字符串是否相等。
public boolean isIsomorphic1(String s, String t) {
if (s.length() != t.length())
return false;
if (transferStr(s).equals(transferStr(t)))
return true;
return false;
}
public String transferStr(String s) {
Map<String, Integer> map = new HashMap<String, Integer>();
String str = "", strTemp = "";
int temp = 0;
for (int i = 0; i < s.length(); i++) {
strTemp = s.charAt(i) + "";
if (!map.containsKey(strTemp)) {
map.put(s.charAt(i) + "", temp++);
}
str = str + map.get(strTemp);
}
return str;
}
很可惜,想法是好的,但是超时不能Accept。
方法二:建一个map保存映射关系, 同时用一个set保持被映射的char, 保证同一个char 不会被映射两次。
public boolean isIsomorphic2(String s, String t) {
if (s == null || t == null)
return false;
if (s.length() != t.length())
return false;
Map<Character, Character> map = new HashMap<Character, Character>();
Set<Character> set = new HashSet<Character>();
char c1, c2;
for (int i = 0; i < s.length(); i++) {
c1 = s.charAt(i);
c2 = t.charAt(i);
if (map.containsKey(c1)) {
if (map.get(c1) != c2)
return false;
} else {
if (set.contains(c2))
return false;
else {
map.put(c1, c2);
set.add(c2);
}
}
}
return true;
}