Implement strStr() - LeetCode

题目链接

Implement strStr() - LeetCode

注意点

  • 输入的数组是无序的

解法

解法一:暴力解法,当haystack[i]等于needle[0]的时候说明接下来的串有可能会是needle, 于是我们逐个遍历判断是否真的是needle。时间复杂度为O(nm)

class Solution {
public:
    int strStr(string haystack, string needle) {
        int l = needle.size(),n = haystack.length();
        if(l == 0)
        {
            return 0;
        }
        if(n < l)
        {
            return -1;
        }
        int i,j;
        for(i = 0;i < n;i++)
        {
            if(haystack[i] == needle[0])
            {
                bool flag = true;
                for(j = 0;j < l;j++)
                {
                    if(haystack[i+j] != needle[j])
                    {
                        flag = false;
                        break;
                    }
                }
                if(flag) return i;
            }
        }
        return -1;
    }
};

解法二:又是一个stl函数。时间复杂度为O(n)

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);
    }
};

解法三:要用到KMP算法,留待以后补上~~

小结

  • 今天猛然发现自己似乎太多题目用C++封装好的函数来解了,已经违背了自己刷LeetCode是为了复习算法的初衷,变成了毫无意义的刷题发博客...以后要注意这一点了...

猜你喜欢

转载自www.cnblogs.com/multhree/p/10350937.html