admin管理员组

文章数量:1636966

Implement strStr()

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


这题的最佳解法当然是KMP算法,但是暴力比对也能解决问题了,之后一定要好好学习KMP算法。

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        //should use the kmp algorithm, but this one didn't use it

        int finalup = strlen(haystack) - strlen(needle);
        int lengthNeedle = strlen(needle);

        if (finalup < 0)
            return -1;

        for (int i = 0; i < finalup + 1; i++)
        {
            int j = 0, count = i;
            for (j = 0; j < lengthNeedle; )
            {
                if (haystack[count] == needle[j])
                {
                    count++;
                    j++;
                }
                else
                    break;
            }

            if (j == lengthNeedle)
                return i;
        }

        return -1;
    }
};

本文标签: LeetCodestrStrimplement