題目描述
Given two strings s and t, determine if they are isomorphic. Two strings are isomor-
phic if the characters in s can be replaced to get t.
For example,”egg” and “add” are isomorphic, “foo” and “bar” are not.
給定兩個串s和t,確定它們是否是同構的。
如果s中的字符可以被替換得到t,那麼兩個字符串是同構的。
例如,“egg”和“add”是同構的,“foo”和“bar”不是同構的。
題目解析
我們需要定義一個函數,參數爲map和value,返回在map中的value的key。爲了判斷同構我們分三種情況,同K,不同V;同V,不同K;同K,同V的情況。
AC代碼
import java.util.HashMap;
import java.util.Map;
public class Solution {
public boolean isIsomorphic(String s, String t) {
if (s == null || t== null) {
return false;
}
if (s.length() != t.length()) {
return false;
}
if (s.length() == 0 && t.length() == 0) {
return true;
}
HashMap<Character, Character> hashMap = new HashMap<Character, Character>();
for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
Character c = getKey(hashMap, c2);
//三種情況。情況1:同K,不同V 例如foo和bar。情況2:同V,不同K,例如bar和foo。情況3,將字符放入map
if (c != null && c != c1) {
return false;
}else if (hashMap.containsKey(c1)) {
if (c2 != hashMap.get(c1)) {
return false;
}
}else {
hashMap.put(c1, c2);
}
}
return true;
}
/*
* a method for getting key of a target value
* */
public Character getKey(HashMap<Character, Character> map, Character target) {
for (Map.Entry<Character, Character> entry: map.entrySet()) {
if (entry.getValue().equals(target)) {
return entry.getKey();
}
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution solution = new Solution();
System.out.println("同K,同V:" + solution.isIsomorphic("egg", "add"));
System.out.println("同K,不同V:" + solution.isIsomorphic("foo", "bar"));
System.out.println("同V,不同K:" + solution.isIsomorphic("bar", "foo"));
}
}