-
来源:领扣 leetcode 28. 实现strStr()
-
题目:实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。- 示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2 - 示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1 - 说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
- 示例 1:
-
做法1:遍历haystack,利用subString(),找到needle的位置
public int strStr(String haystack, String needle) {
int len1 = haystack.length();
int len2 = needle.length();
if (len1 < len2) {
return -1;
} else if (len2 == 0) {
return 0;
}
int num = len1 - len2;
for (int i = 0; i <= num; i++) {
if (haystack.substring(i, i + len2).equals(needle)) {
return i;
}
}
return -1;
}
- 做法2:和做法1类似,只不过把subString()换成了chatAt()
public int strStr2(String haystack, String needle) {
int len1 = haystack.length();
int len2 = needle.length();
if (len1 < len2) {
return -1;
} else if (len2 == 0) {
return 0;
}
int num = len1 - len2;
for (int i = 0; i <= num; i++) {
int count = 0;
while (count < len2 && haystack.charAt(count + i) == needle.charAt(i)) {
count++;
}
if (count == len2)
return i;
}
return -1;
}
- 做法3:KMP,程序理解起来有点困难的话,就多调式,会好很多。
public int strStr3(String haystack, String needle) {
int len1 = haystack.length();
int len2 = needle.length();
if (len1 < len2) {
return -1;
} else if (len2 == 0) {
return 0;
}
int[] prefix = getPrefix(needle);
int i = 0, j = 0;
char[] text = haystack.toCharArray();
char[] pattern = needle.toCharArray();
while (i < len1) {
if (j == len2 - 1 && text[i] == pattern[j]) return i - j;
if (text[i] == pattern[j]) {
i++;
j++;
} else {
j = prefix[j];
if (j == -1) {
i++;
j++;
}
}
}
return -1;
}
/*
功能:
字符串 a b a b
0 0 1 2
所求 -1 0 0 1
多多调试有助于更好地理解:
a b a b a d
0 0 1 2 3 0
-1 0 0 1 2 3
*/
private int[] getPrefix(String needle) {
//给定字符串:a b a b
char[] arr = needle.toCharArray();
int arrLen = arr.length;
//记录最左前缀相同的长度
int prefixLen = 0;
int i = 1;
int[] prefix = new int[arrLen];
prefix[0] = 0;
//第一步求得 0 0 1 2
while (i < arrLen) {
if (arr[i] == arr[prefixLen]) {
prefixLen++;
prefix[i] = prefixLen;
i++;
} else {
if (prefixLen > 0) prefixLen = prefix[prefixLen - 1];
else {
prefix[i] = 0;
i++;
}
}
}
//第二步求得 -1 0 0 1
int index = prefix.length - 1;
while (index > 0) {
prefix[index] = prefix[index - 1];
index--;
}
prefix[0] = -1;
return prefix;
}
可以参考:讲解的十分详细
从头到尾彻底理解KMP(2014年8月22日版)
字符串匹配KMP算法的讲解C++
实现strStr()函数详解
1312

被折叠的 条评论
为什么被折叠?



