找出字符串第一个匹配的下标
给你两个字符串
haystack
和needle
,请你在haystack
字符串中找出needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果needle
不是haystack
的一部分,则返回-1
。示例 1:
输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。 第一个匹配项的下标是 0 ,所以返回 0 。示例 2:
输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
方法一:KMP算法
class Solution {
public int strStr(String haystack, String needle) {
int[] next = getNext(needle);
int n = haystack.length();
int i = 0, j = 0;
while (i < n) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
if (j == needle.length()) {
return i - j;
}
} else {
if (j != 0) {
j = next[j - 1];
} else {
i++;
}
}
}
return -1;
}
public int[] getNext(String needle) {
int n = needle.length();
int[] next = new int[n];
next[0] = 0;
int lcp = 0;
int i = 1;
while (i < n) {
if (needle.charAt(i) == needle.charAt(lcp)) {
lcp++;
next[i] = lcp;
i++;
} else {
if (lcp != 0) {
lcp = next[lcp - 1];
} else {
next[i] = 0;
i++;
}
}
}
return next;
}
}
时间复杂度 T(n) = O(m + n)
方法二: 蛮力法
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
for (int i = 0; i + m <= n; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
}
依次比较主串和字串即可,时间复杂度T(n) = O(m * n)