Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
题目不难,但是有几个问题:
1.字符串结束的判断用'\0',字符串完全结束判断用NULL
2.题目里说的是needle为空返回0,不是说haystack
3.return要放在最后一个大括号里,否则会报错control reaches end of non-void function [-Werror=return-type]
4.strlen(char *)可以直接获得数组长度;
5.strstr(str1,str2)函数用于判断字符串str2是否是str1的子串,如果是则该函数返回str2在str1中首次出现的地址,否则返回NULL。
初始代码如下:
int strStr(char* haystack, char* needle) {
int index,i=0,j,flag;
if(needle[0]==NULL){return 0;}//判断字符串结束用needle[0]=='\0',用NULL多走了一次循环;
else{
while(haystack[i]!=NULL)
{
if(haystack[i]==needle[0]){
index=i;
j=0;
while(needle[j]!=NULL)
{
if(needle[j]==haystack[i])
{i++;j++;flag=1;}
else{flag=0;break;}
}
if(flag==1&&needle[j]==NULL){return index;}
else{i=index+1;}
}
else{i++;}
}
if(flag==0){return -1;}//这样的return会报错control reaches end of non-void function [-Werror=return-type],再往外放一层就可以了
}
}
但跑出来效率很低,参考0ms的代码如下:
int strStr(char* haystack, char* needle) {
int i,j=0;
char *s;
if((strlen(needle)==0))return 0;//strlen(char *)可以直接获得数组长度;
if(strlen(needle)==0 && strlen(haystack)==0)return 0;
if(strstr(haystack,needle)==NULL)return -1;//strstr(str1,str2)函数用于判断字符串str2是否是str1的子串,如果是则该函数返回str2在str1中首次出现的地址,否则返回NULL
else
{
return strstr(haystack,needle)-haystack;//地址值可能是很大的数值,应该输出对于haystack首地址的位移值
}
return -1;
}
java版本:
class Solution {
public int strStr(String haystack, String needle) {
int len=needle.length();
if(len==0){
return 0;
}
if(haystack.indexOf(needle)!=-1){
return haystack.indexOf(needle);
}
else{
return -1;
}
//indexOf(String s)的在java中的使用,如果包含则返回的值是包含该子字符串在父类字符串中起始位置,如果不包含必定全部返回值为-1;//父类为空时的返回值为-1,表示不包含;
}
}