Isomorphic Strings
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.
这题需要注意的地方是我们要从S到T 和T到S都检查一遍。
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 if (s.length() != t.length()) return false; 4 5 Map<Character, Character> map = new HashMap<>(); 6 7 for (int i = 0; i < s.length(); i++) { 8 char chKey = s.charAt(i); 9 char chValue = t.charAt(i); 10 11 if(map.containsKey(chKey)) { 12 char value = map.get(chKey); 13 if (value != chValue) { 14 return false; 15 } 16 } else { 17 map.put(chKey, chValue); 18 } 19 } 20 21 map.clear(); 22 23 for (int i = 0; i < s.length(); i++) { 24 char chKey = t.charAt(i); 25 char chValue = s.charAt(i); 26 27 if(map.containsKey(chKey)) { 28 char value = map.get(chKey); 29 if (value != chValue) { 30 return false; 31 } 32 } else { 33 map.put(chKey, chValue); 34 } 35 } 36 37 return true; 38 } 39 }