28. Implement strSTr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

解法1:

C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || haystack == null) {
return -1;
}
int n = haystack.length(), m = needle.length();
if (m > n) {
return -1;
}
for (int i = 0; i <= n - m; i++) {
if (haystack.substring(i, i + m).equals(needle)) {
return i;
}
}
return -1;
}
}