题目原文:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目大意:
实现strStr()函数。返回needle字符串在haystack字符串中首次出现的下标,如果needle不是haystack的子串则返回-1.
题目分析:
c99中strstr函数的接口不对,因此使用Java中的indexOf()方法水过。
源码:(language:java)
public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
成绩:
1ms,beats 69.31%,众数1ms,29.29%.
cmershen的碎碎念:
附C99中strstr()函数源码:
char *strstr(constchar*s1,constchar*s2)
{
int n;
if(*s2)
{
while(*s1)
{
for(n=0;*(s1+n)==*(s2+n);n++)
{
if(!*(s2+n+1))
return(char*)s1;
}
s1++;
}
return NULL;
}
else
return (char*)s1;
}
但是稍加改动(简单改动了一下return的部分)之后放入OJ居然会提示TLE!也许C99的源码存在问题有待思考。
再附jdk中indexOf的底层实现供研究:
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;
}