目录
给你两个字符串 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 。
提示:
1 <= haystack.length, needle.length <= 104
haystack
和needle
仅由小写英文字符组成
本人解法:
将对应的字符串替换成字符"1",然后遍历字符串,判断替换后的字符串下标位置吗,并返回,如果未匹配到,则返回-1;
class Solution {
public int strStr(String haystack, String needle) {
haystack = haystack.replace(needle, "1");
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == '1') {
return i;
}
}
return -1;
}
}
官方解答:
方法一:暴力匹配
思路及算法
我们可以让字符串 needle\textit{needle}needle 与字符串 haystack\textit{haystack}haystack 的所有长度为 mmm 的子串均匹配一次。
为了减少不必要的匹配,我们每次匹配失败即立刻停止当前子串的匹配,对下一个子串继续匹配。如果当前子串匹配成功,我们返回当前子串的开始位置即可。如果所有子串都匹配失败,则返回 −1-1−1。
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;
}
}
复杂度分析
时间复杂度:
O(n×m)O(n \times m)O(n×m),其中 nnn 是字符串 haystack\textit{haystack}haystack 的长度,mmm 是字符串 needle\textit{needle}needle 的长度。最坏情况下我们需要将字符串 needle\textit{needle}needle 与字符串 haystack\textit{haystack}haystack 的所有长度为 mmm 的子串均匹配一次。
空间复杂度:
O(1)O(1)O(1)。我们只需要常数的空间保存若干变量。