28. Implement strStr()
2018-02-09 本文已影响0人
wtmxx
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
一道字符串匹配题,java里String类已经有了实现。
看一下源码
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
发现他采取的办法是暴力破解,找第一个匹配字符串然后挨个往后比,时间复杂度最好O(N),最坏O(N*M)
但他平均效率是比不了KMP,BM,SUNDAY等算法的。