-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsomorphicStringM1.java
More file actions
37 lines (31 loc) · 1006 Bytes
/
IsomorphicStringM1.java
File metadata and controls
37 lines (31 loc) · 1006 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
36
37
import java.util.Arrays;
/**
* Leetcode problem #205, Isomorphic Strings (Approach 1)
* https://leetcode.com/problems/isomorphic-strings
*
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class IsomorphicStringM1 {
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) {
if (s.length() != t.length())
return false;
int[] arr1 = new int[256], arr2 = new int[256];
Arrays.fill(arr1, -1);
Arrays.fill(arr2, -1);
for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i), c2 = t.charAt(i);
if (arr1[c1] == -1 && arr2[c2] == -1) {
arr1[c1] = c2;
arr2[c2] = c1;
} else if (arr1[c1] != c2 || arr2[c2] != c1)
return false;
}
return true;
}
}