集册 LeetCode 题解 27.Implement strStr()(实现 strStr() 函数)

27.Implement strStr()(实现 strStr() 函数)

—— Implement strStr()(实现 strStr() 函数)

欢马劈雪     最近更新时间:2020-08-04 05:37:59

156

翻译

实现 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;
    }
};

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

展开阅读全文