LeetCode28-实现strStr()

LeetCode28-实现strStr()

通过切割字符串实现

1
2
3
4
5
6
7
8
9
10
11
12
13
public int strStr(String haystack, String needle) {
int n = needle.length();
if (n == 0) {
return 0;
}
//haystack = "hello", needle = "ll"
for (int i = 0; i < haystack.length(); i++) {
if (i + n <= haystack.length() && haystack.substring(i, i + n).equals(needle)) {
return i;
}
}
return -1;
}