-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsomorphicStringM2.java
More file actions
35 lines (28 loc) · 973 Bytes
/
IsomorphicStringM2.java
File metadata and controls
35 lines (28 loc) · 973 Bytes
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
import java.util.HashMap;
/**
* Leetcode problem #205, Isomorphic Strings (Approach 2)
* https://leetcode.com/problems/isomorphic-strings
*/
public class IsomorphicStringM2 {
public static void main(String[] args) {
String s = "paper", t = "title";
boolean isIsomorphic = isIsomorphic(s, t);
System.out.println(isIsomorphic);
}
public static boolean isIsomorphic(String s, String t) {
return transformString(s).equals(transformString(t));
}
public static String transformString(String s) {
StringBuilder builder = new StringBuilder();
HashMap<Character, Integer> map = new HashMap<>();
for (int i=0; i<s.length(); i++) {
char c1 = s.charAt(i);
if (!map.containsKey(c1)) {
map.put(c1, i);
}
builder.append(Integer.toString(map.get(c1)));
builder.append(" ");
}
return builder.toString();
}
}