友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
解题分析
直接截取字符串然后判断相等,算不算作弊?😆
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
public int strStr(String haystack, String needle) {
if (Objects.isNull(needle) || needle.length() == 0) {
return 0;
}
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
String sub = haystack.substring(i, i + needle.length());
if (needle.equals(sub)) {
return i;
}
}
}
return -1;
}
// TODO 有必要学一下 KMP 算法了啊!
public int strStr1(String source, String target) {
if (source == null || target == null || target.length() > source.length()) {
return -1;
}
if (target.length() == 0) {
return 0;
}
char[] sA = source.toCharArray();
char[] tA = target.toCharArray();
for (int i = 0; i < source.length(); i++) {
if (contain(sA, i, tA)) {
return i;
}
}
return -1;
}
private boolean contain(char[] source, int index, char[] target) {
if (source.length - index < target.length) {
return false;
}
for (int i = index, j = 0; j < target.length; i++, j++) {
if (source[i] != target[j]) {
return false;
}
}
return true;
}