-
Notifications
You must be signed in to change notification settings - Fork 0
/
IsomorphicString.java
60 lines (56 loc) · 1.49 KB
/
IsomorphicString.java
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
import java.util.Map;
import java.util.HashMap;
public class IsomorphicString{
public static boolean checkWith2Maps(String s1, String s2){
if(s1.length() != s2.length())
return false;
if(s1.length() == 0)
return true;
Map<Character, Character> m1 = new HashMap<Character, Character>();
Map<Character, Character> m2 = new HashMap<Character, Character>();
char c1, c2;
for(int i = 0; i < s1.length(); i++){
c1 = s1.charAt(i);
c2 = s2.charAt(i);
if(m1.get(c1) != null){
if(m1.get(c1) != c2)
return false;
} else if(m2.get(c2) != null){
return false;
} else {
m1.put(c1, c2);
m2.put(c2, c1);
}
}
return true;
}
public static boolean checkWith1Map(String s1, String s2){
if(s1.length() != s2.length())
return false;
if(s1.length() == 0)
return true;
Map<Character, Character> m = new HashMap<Character, Character>();
char c1, c2;
for(int i = 0; i < s1.length(); i++){
c1 = s1.charAt(i);
c2 = s2.charAt(i);
if(m.get(c1) != null){
if(m.get(c1) != c2)
return false;
} else if(m.containsValue(c2)){
return false;
} else {
m.put(c1, c2);
}
}
return true;
}
public static void main(String[] argvs){
System.out.println(checkWith1Map("bar", "foo"));
System.out.println(checkWith2Maps("bar", "foo"));
System.out.println(checkWith1Map("foo", "bar"));
System.out.println(checkWith2Maps("foo", "bar"));
System.out.println(checkWith2Maps("abc", "def"));
System.out.println(checkWith1Map("abc", "def"));
}
}