DAY 44 leetcode 28--字符串.实现strStr()
题号28
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
我的解法
双指针,slow定位,fast比较,成功则返回,失败则往前进
class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) {
return 0;
}
int slow = 0;
int fast = 0;
int count = 0;
int size1 = haystack.length();
int size2 = needle.length();
if (size1 < size2) {
return -1;
}
while (fast < size1 - size2 + 1) {
slow = fast;
count = 0;
for (int i = 0; i < size2; i++) {
if (needle.charAt(i) == haystack.charAt(fast)) {
fast++;
count++;
if (count == size2) {
return slow;
}
} else {
fast = slow + 1; // 移动fast指针到下一个可能的起始位置
break;
}
}
}
return -1;
}
}