找出字符串中第一个匹配项的下标
- 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:“sad” 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
解题思路
- 这是一个经典的字符串匹配问题,可以使用双指针技巧来实现。
- 将两个指针分别指向 haystack 和 needle 的开头,然后逐个字符地比较,直到找到第一个匹配项或者遍历完 haystack 字符串。
Java实现
public class StrStr {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
//遍历haystack字符串
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
int j;
//遍历needle,needle字符串从0匹配haystack
for (j = 0; j < needle.length(); j++) {
//当前字母不匹配,直接终止内层循环
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
//如果j==needle的长度,证明haystack有字符串和needle完全匹配上了
if (j == needle.length()) {
return i;//返回匹配的开始位置
}
}
return -1;
}
public static void main(String[] args) {
StrStr strStr = new StrStr();
String haystack1 = "hello", needle1 = "ll";
System.out.println("Index of First Occurrence: " + strStr.strStr(haystack1, needle1)); // Expected: 2
String haystack2 = "aaaaa", needle2 = "baa";
System.out.println("Index of First Occurrence: " + strStr.strStr(haystack2, needle2)); // Expected: -1
}
}
时间空间复杂度
- 时间复杂度: 在最坏情况下,时间复杂度为 O((n-m+1)*m),其中 n 是 haystack 的长度,m 是 needle 的长度。
- 空间复杂度: 使用了常数级的额外空间,空间复杂度为 O(1)。