博客园:https://www.cnblogs.com/baozitraining/p/11112125.html
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.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
Problem link
You can find the detailed video tutorial here
A relatively straightforward problem, very similar to Word Pattern. All we have to do is check the one to one mapping from string a to string b, also it needs to maintain a bijection mapping (meaning no two different characters in a should map to the same character in b)
Check character one by one from a and b. If char in a hasn't been seen before, create a one to one mapping between this char in a and the char in b so later if this char in a is seen again, it has to map to b, else we return false. Moreover, need to make sure the char in b is never mapped by a different character.
1 public boolean isIsomorphic(String a, String b) {
2 if (a == null || b == null || a.length() != b.length()) {
3 return false;
4 }
5 Map<Character, Character> lookup = new HashMap<>();
6 Set<Character> dupSet = new HashSet<>();
7
8 for (int i = 0; i < a.length(); i++) {
9 char c1 = a.charAt(i);
10 char c2 = b.charAt(i);
11
12 if (lookup.containsKey(c1)) {
13 if (c2 != lookup.get(c1)) {
14 return false;
15 }
16 } else {
17 lookup.put(c1, c2);
18 // this to prevent different c1s map to the same c2, it has to be a bijection mapping
19 if (dupSet.contains(c2)) {
20 return false;
21 }
22 dupSet.add(c2);
23 }
24 }
25 return true;
26 }
Time Complexity: O(N), N is the length of string a or string b
Space Complexity: O(N), N is the length of string a or string b because the hashmap and set we use