美文网首页
28. Implement strStr()

28. Implement strStr()

作者: syuhung | 来源:发表于2020-06-09 18:44 被阅读0次

    Implement strStr().

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

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1

    Clarification:

    What should we return when needle is an empty string? This is a great question to ask during an interview.

    For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().


    题目大意:

      给定两个字符串haystackneedle,找出needlehaystack中首次出现的位置。如果没找到则返回-1,并且当needle是空串的时候返回0。

    解题思路:

      简单呐~~~~~~~~~~~~~~~~直接haystack.find(needle)(手动滑稽

      也确实是简单,要查找肯定需要一次遍历,没什么好说的。

      从头开始遍历,每次遍历取临时遍历temp与当前遍历下标相同,若遍历needle.size()次后完全匹配则直接返回当前的遍历下标即可

    解题代码:

    class Solution {
    public:
        int strStr(string haystack, string needle) {
        //空串返回0
        if (needle.empty())
            return 0;
        //needle长度比haystack大时返回-1
        if (needle.size() > haystack.size())
            return -1;
        size_t haySize = haystack.size(), needSize = needle.size();
        int res = -1, temp;
        //循环不变量是剩余未遍历字符长度与needle长度之和小于或等于haystack长度
        for (size_t hayIndex = 0, needIndex = 0; hayIndex + needSize <= haySize; ++hayIndex, needIndex = 0)
        {
            temp = hayIndex;
            //注意needIndex得小于needSize,不然会越界
            while (needIndex < needSize && haystack[temp] == needle[needIndex]) {
                ++temp;
                ++needIndex;
            }
            if (needIndex == needSize)
            {
                res = hayIndex;
                break;
            }
        }
        return res;
      }
    };
    

    相关文章

      网友评论

          本文标题:28. Implement strStr()

          本文链接:https://www.haomeiwen.com/subject/qosetktx.html