題目
描述
實現 strStr()
函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當 needle
是空字符串時,我們應當返回什么值呢?這是一個在面試中很好的問題。
對于本題而言,當 needle
是空字符串時我們應當返回 0 。這與C語言的 strstr()
以及 Java的 indexOf()
定義相符。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-strstr
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
解答
思路
找到indexOf的源碼,簡化了一下,沒有KMP算法高效。但是也不會超時。
代碼
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() > haystack.length()) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
char first = needle.charAt(0);
int max = haystack.length() - needle.length();
for (int i = 0; i <= max; i++) {
if (first != haystack.charAt(i)) {
while (++i <= max && haystack.charAt(i) != first) ;
}
if (i <= max) {
int j = i + 1;
int end = j + needle.length() - 1;
for (int k = 1; j < end && haystack.charAt(j)
== needle.charAt(k); j++, k++) ;
if (j == end) return i;
}
}
return -1;
}
}