LeetCode 28. Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

这个题目就是在一个字符串中找到另外一个字符串第一次出现的地方。在数据结构这本书中有关于字符串匹配的算法——KMP算法

时间复杂度可以为O(n+m) n和m分别为两个字符串的长度,我就直接采用大家都能想到的算法,逐个的匹配,代码也比较简单

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (haystack.size() < needle.size())return -1;
        for (int i = 0;i <= haystack.size() - needle.size();++i)
        {
            int temp = i,j=0;
            for (;j <  needle.size();++temp,++j)
            {
                if (haystack[temp] != needle[j])break;
            }
            if (needle.size() == j)return i;
        }
        return -1;
    }
};
原文地址:https://www.cnblogs.com/csudanli/p/5879161.html