leetcode28实现strStr()
程序员文章站
2024-03-22 13:38:52
...
暴力法
class Solution {
public int strStr(String haystack, String needle) {
int len_hay = haystack.length();
int len_needle = needle.length();
int j = 0;
int i = 0;
if (len_needle==0)
return 0;
if (len_needle > len_hay)
return -1;
for (i = 0; i < len_hay; i++) {
if (j == len_needle) {
return i - len_needle;
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
else {
i = i -j;
j = 0;
}
}
if (j == len_needle) {
return i - len_needle;
}
return -1;
}
}
上一篇: Set