题目描述:实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)

输入示例1:
输入: haystack = "hello", needle = "ll"
输出: 2
输入示例2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1

算法思想:
方法1:暴力法求解,从母字符串的第一个位置开始截取子字符串长度的子字符串,然后比较两个字符串是否相等。

class Solution {
public:
int strStr(string haystack, string needle) {
if(needle=="")
return 0;
int len1=haystack.size();
int len2=needle.size();
bool flag=false;
for(int i=0;i<len1-len2+1;i++){
string subs=haystack.substr(i,len2);
if(subs.compare(needle)==0)
return i;
}
return -1;
}
};

LeetCode_28_Implement strStr()_实现strStr()_字符串


更简单的调用库函数的方法:

class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
int pos=haystack.find(needle);
return pos;
}
};

LeetCode_28_Implement strStr()_实现strStr()_字符串长度_02