返回

[Leetcode]28. Implement strStr()(C++)

题目描述

题目链接:28. Implement strStr()

Implement strStr().

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

例子

例子 1

Input: haystack = “hello”, needle = “ll” Output: 2

例子 2

Input: haystack = “aaaaa”, needle = “bba” Output: -1

例子 3

Input: Output: Explanation

Follow Up

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().

Constraints

  • haystack and needle consist only of lowercase English characters.

解题思路

这道题思路比较清晰,通过两个指针来解决。其中一个指针 i 遍历 haystack 字符串,另一个指针 ji 开始遍历 needle 的长度,判断每一位是否相同,只要其中一位不同就跳出中间循环将 i 移至下一位。代码如下:

#include <string>

class Solution {
public:
    int strStr(std::string haystack, std::string needle) {
        if (needle.empty()) return 0;
        if (haystack.length() < needle.length()) return -1;
        for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
            int j;
            for (j = 0; j < needle.length(); j++) {
                if (haystack[i + j] != needle[j]) break;
            }
            if (j == needle.length()) return i;
        }
        return -1;
    }
};
  • 时间复杂度: O(mn)
  • 空间复杂度: O(1)
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy