给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
1. 暴力法,分情况讨论
int strStr(string haystack, string needle) {
int slow = 0, fast = 0, flag = -1;
if(haystack.size() < needle.size())
return flag;
if(!needle.size())
return 0;
while(slow < haystack.size())
{
if(haystack[slow]!=needle[fast])
{
if(flag != -1)
slow = flag;
fast = 0;
flag = -1;
}
else if(haystack[slow]==needle[fast])
{
if(flag==-1) flag = slow;
fast ++;
if(fast==needle.size()) return flag;
}
slow ++;
}
return (needle.size() == fast)?flag:-1;
}
2. 利用find函数
int strStr(string haystack, string needle) {
int pos=haystack.find(needle);
return pos;
}
3. 利用substr函数
int strStr(string haystack, string needle) {
if(haystack.size()<needle.size()) return -1;
for(int i=0;i<haystack.size()-needle.size()+1;i++){
//也可添加判断条件,当首字母相同时才进行字符串的切割
if(haystack.substr(i,needle.size())==needle) return i;
}
return -1;
}
4. 暴力解法之回溯(法1的简写)
int strStr(string haystack, string needle) {
int i=0,j=0;
while(i<haystack.size()&&j<needle.size()){
if(haystack[i]==needle[j]) i++,j++;
else i=i-j+1,j=0;
}
if(j==needle.size()) return i-j;
return -1;
}
5. 暴力解法之遍历
int n = haystack.size(), m = needle.size();
for(int i = 0; i < n - m + 1; i ++)
{
for(int j = 0; ; j < m; j ++)
{
if(haystack[i + j] != needle[j])
break;
}
if(j == m)
return i;
}
return -1;
}