Leetcode(10)-实现strStr()

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

当 needle 是空字符串时我们应当返回 0 。

一开始的思路:用i和j从头开始分别遍历haystack和needle字符串,先固定j,直到i所指的字母与needle的首字符相等的时候,停止遍历。然后i和j开始同时向后遍历,如果有不相等的,就返回-1,直到有一个字符串先到头。若haystack先到头,则返回-1,若needle先到头或者同时到头,则返回i-needle.size()

这样的思路有一个问题,就是mississip和issip这种字符串,就是母串如果先出现一个类似子串但又不等于子串的部分,会造成干扰。

所以这里我们换个思路:我们在母串中,依次遍历子串长度的子串,看看能否找到和子串相等的部分,这样就不会漏掉上述的部分。

int strStr(string haystack, string needle) 
{
        if (needle.empty()) return 0;
        int m = haystack.size(), n = needle.size();
        if (m < n) return -1;
        for (int i = 0; i <= m - n; ++i) 
     {
int j = 0; for (j = 0; j < n; ++j)
       {
if (haystack[i + j] != needle[j]) break; } if (j == n)
           return i; } return -1; }

其实我们还可以利用string类中的现成的find函数

int strStr(string haystack, string needle) 
{
    string::size_type index = haystack.find(needle);
    return index == string::npos ? -1 : index;
}

find函数只用了第一个参数,默认是从母串的开头查找,找到和needle相同的子串就停止,返回位置,若找不到,则返回string::npos。

猜你喜欢

转载自www.cnblogs.com/mini-coconut/p/8977752.html