28.实现函数strSTR()

来源:互联网 发布:数学必修三算法用学吗 编辑:程序博客网 时间:2024/06/10 15:43

Implement strStr()

问题描述:

Implement strStr().

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

测试代码:

class Solution {public:    int strStr(string haystack, string needle) {        if(haystack.length()<needle.length())            return -1;        if(needle.length()==0)            return 0;        for(int i=0;i<haystack.length()-needle.length()+1;i++)        {            if(haystack.substr(i,needle.length())==needle)                return i;        }        return -1;    }};

性能:

这里写图片描述

参考答案:

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

性能:

这里写图片描述