LeetCode28-实现strStr()

题目链接

英文链接:https://leetcode.com/problems/implement-strstr/

中文链接:https://leetcode-cn.com/problems/implement-strstr/

题目详述

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1

示例 1:

1
2
输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

1
2
输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:

needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf()) 定义相符。

题目详解

Java 中 String 的 indexOf 方法实现了类似于 strStr() 查找字符串的功能,可以直接使用。

1
2
3
4
5
6
public class LeetCode_00028 {

public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}

不过本题是实现这个功能,自然不能调用这个方法,自己写一下就可以了。注意判断当 needle 是空字符串时应当返回 0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class LeetCode_00028 {

public int strStr(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
int max = haystack.length() - needle.length();
for (int i = 0; i <= max; ++i) {
// 找到第一个相等的字符
if (haystack.charAt(i) == needle.charAt(0)) {
int j = i + 1;
for (int k = 1; k < needle.length()
&& haystack.charAt(j) == needle.charAt(k); ++k, ++j);
// 找到整个字符串就返回
if (j == i + needle.length()) {
return i;
}
}
}
return -1;
}
}

也可以用 KMP 算法。

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
65
public class LeetCode_00028 {

// public int strStr(String haystack, String needle) {
// return haystack.indexOf(needle);
// }

// public int strStr(String haystack, String needle) {
// if (needle.length() == 0) {
// return 0;
// }
// int max = haystack.length() - needle.length();
// for (int i = 0; i <= max; ++i) {
// // 找到第一个相等的字符
// if (haystack.charAt(i) == needle.charAt(0)) {
// int j = i + 1;
// for (int k = 1; k < needle.length()
// && haystack.charAt(j) == needle.charAt(k); ++k, ++j);
// // 找到整个字符串就返回
// if (j == i + needle.length()) {
// return i;
// }
// }
// }
// return -1;
// }

// KMP
public int strStr(String haystack, String needle) {
int[] next = getNextArray(needle);
int i = 0;
int j = 0;
while (i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
++i;
++j;
} else if (next[j] != -1) {
j = next[j];
} else {
++i;
}
}
return j == needle.length() ? i - j : -1;
}

private int[] getNextArray(String s) {
if (s.length() <= 1) {
return new int[] { -1 };
}
int[] next = new int[s.length()];
next[0] = -1;
next[1] = 0;
int len = 0;
int i = 2;
while (i < s.length()) {
if (s.charAt(i - 1) == s.charAt(len)) {
next[i++] = ++len;
} else if (len > 0) {
len = next[len];
} else {
next[i++] = 0;
}
}
return next;
}
}