admin管理员组

文章数量:1636896

翻译

实现strStr()函数。

返回针(needle)在草垛/针垛(haystack)上第一次出现的索引, 如果不存在其中则返回-1。

其实也就是说字符串str2在字符串str1中第一次出现的索引而已。

原文

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:
    bool compare(string s1, int index, string s2) {
        int count = 0;
        for (int i = 0; i < s2.length(); i++) {
            if (s2[i] == s1[i + index])
                count++;
        }
        if (count == s2.length())
            return true;
        return false;
    }         
    int strStr(string haystack, string needle) {
        for (int i = 0; i < haystack.length(); i++) {
            if (haystack[i] == needle[0]) {
                if (compare(haystack, i, needle))
                    return i;
            }
        }
        return -1;
    }
};

发现超时了……其实在测试之前就看到了别人的答案……惊呆了……这样都可以?

 class Solution {
    public:
        int strStr(string haystack, string needle) {

            return haystack.find(needle);

        }
    };

也算是长见识了……

本文标签: 函数LeetCodestrStrimplement