-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetermine If One String Is Another's Substring II.java
64 lines (56 loc) · 1.76 KB
/
Determine If One String Is Another's Substring II.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
61
62
63
64
/*
Implement strStr function in O(n + m) time.
strStr return the first index of the target string in a source string.
The length of the target string is m and the length of the source string is n.
If target does not exist in source, just return -1.
Example
Given source = abcdef, target = bcd, return 1.
time = O(n + m)
space = O(1)
*/
public class Solution {
private final int BASE = 1000000;
public int strStr2(String source, String target) {
// write your code here
if (source == null || target == null) {
return -1;
}
if (source.length() - target.length() < 0) {
return -1;
}
int m = target.length();
if (m == 0) {
return 0;
}
// for remove the earliest element
int power = 1;
for (int i = 0; i < m; i++) {
power = (power * 31) % BASE;
}
// for target hashCode
int targetCode = 0;
for (int i = 0; i < m; i++) {
targetCode = (targetCode * 31 + target.charAt(i)) % BASE;
}
// Looking for target in source
int hashCode = 0;
for (int i = 0; i < source.length(); i++) {
hashCode = (hashCode * 31 + source.charAt(i)) % BASE;
if (i < m - 1) {
continue;
}
if (i >= m) {
hashCode -= (source.charAt(i - m) * power) % BASE;
if (hashCode < 0) {
hashCode += BASE;
}
}
if (hashCode == targetCode) {
if (source.substring(i - m + 1, i + 1).equals(target)) {
return i - m + 1;
}
}
}
return -1;
}
}