-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIsomorphicStrings.java
More file actions
67 lines (57 loc) · 1.98 KB
/
IsomorphicStrings.java
File metadata and controls
67 lines (57 loc) · 1.98 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
package Leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* @author kalpak
* 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.
*/
public class IsomorphicStrings {
public static boolean isIsomorphic(String s, String t) {
// Two strings are isomorphic
// if the positions of the characters follow the same pattern.
// So using maps to compare the position patterns.
if(s == null || t == null)
return false;
if(s.length() != t.length())
return false;
Map<Character, Integer> sIndex = new HashMap<>();
Map<Character, Integer> tIndex = new HashMap<>();
// Whether the two strings are isomorphic can be judged by the index patterns.
// In the above example, these two strings are isomorphic with the same index patterns.
for(int i = 0; i < s.length(); i++) {
int sIdx = sIndex.getOrDefault(s.charAt(i), -1);
int tIdx = tIndex.getOrDefault(t.charAt(i), -1);
if(sIdx != tIdx)
return false;
sIndex.put(s.charAt(i), i);
tIndex.put(t.charAt(i), i);
}
return true;
}
public static void main(String[] args) {
System.out.println(isIsomorphic("egg", "add"));
System.out.println(isIsomorphic("abc", "cde"));
System.out.println(isIsomorphic("paper", "title"));
System.out.println(isIsomorphic("foo", "bar"));
}
}