链接:
https://leetcode.com/problems/implement-strstr/
大意:
找到字符串needle在字符串haystack中首次出现的位置,其中:
若haystack中不含字符串needle,则返回-1
若needle为空串,则返回0
思路:
记haystack的长度为len1,needle的长度为len2,对于字符串haystack中的每个字符Ki(i <= len1-len2),依次比较Ki-K(i+len2-1)是否均与needle中对应字符相同。若都相同,则返回i;否则,继续从haystack的下一字符开始重复上述过程。最后若没找到正确的i,则返回-1
代码:
class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals(""))
return 0;
char[] s1 = haystack.toCharArray(), s2 = needle.toCharArray(); // 将字符串转成字符数组,在之后的访问每个字符的操作时更快
int i = 0;
// 当i+s2.length>s1.length时提前判断不存在匹配
while (i + s2.length <= s1.length) {
int j = i, idx = 0; // j记录s1的字符位置 idx记录s2的字符位置
while (idx < s2.length) {
if (s1[j] != s2[idx])
break;
j++;
idx++;
}
if (idx == s2.length)
return i;
i++;
}
return -1;
}
}
结果:
结论:
记得模式匹配算法的最优解好像是KMP(不会实现...o.o) 没想到普通的匹配都能打败91.68%