-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathStringIsomorphism.java.off
More file actions
72 lines (64 loc) · 2.14 KB
/
StringIsomorphism.java.off
File metadata and controls
72 lines (64 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
https://leetcode.com/problems/isomorphic-strings/
The perfect data structure to solve this is a bimap, which represents a bijection.
There are no bimaps on the stlib: http://stackoverflow.com/questions/9783020/bidirectional-map
but it is easy to simulate them with two separte maps.
*/
import java.util.Map;
import java.util.HashMap;
/*
Current solutions do not consider 4-byte codepoints.
For 2-byte codepoints we could use an array as a map (64kB),
but fro 4-byte codepoints it would be too much.
*/
public class Solution {
/* Double map solution. Duplicates the code, and is marginaly more efficient because it does only a single loop. */
public boolean isIsomorphic(String s, String t) {
int l = s.length();
if (l != t.length())
return false;
Map<Character, Character> mapst = new HashMap<>();
Map<Character, Character> mapts = new HashMap<>();
for (int i = 0; i < l; i++) {
char sc = s.charAt(i);
char tc = t.charAt(i);
Character sm = mapst.get(sc);
Character tm = mapts.get(tc);
if (sm == null) {
mapst.put(sc, tc);
} else {
if (!sm.equals(tc))
return false;
}
if (tm == null) {
mapts.put(tc, sc);
} else {
if (!tm.equals(sc))
return false;
}
}
return true;
}
public boolean isIsomorphicOneSide(String s, String t) {
Map<Character, Character> map = new HashMap<>();
int l = s.length();
for (int i = 0; i < l; i++) {
char sc = s.charAt(i);
char tc = t.charAt(i);
Character mc = map.get(sc);
if (mc == null) {
map.put(sc, tc);
} else {
if (!mc.equals(tc))
return false;
}
}
return true;
}
public boolean isIsomorphic(String s, String t) {
int l = s.length();
if (l != t.length())
return false;
return isIsomorphicOneSide(s, t) && isIsomorphicOneSide(t, s);
}
}