LeetCode算法题28:实现strStr()解析

实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

这个题我竟然首先想到了substring类方法,但是一想那还叫什么算法,相当于直接用了strStr()函数,所以只能自己实现了,这个简单的思路就是直接暴力搜索,很简单,直接一个个搜索haystack然后每一个都搜索needle长度,看是否相符。此外还需要注意题目给定的条件,当haystack长度小于needle长度时一定返回-1,此外当needle为0时返回0。
C++源代码:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1 = haystack.length();
        int len2 = needle.length();
        if (len1<len2)
            return -1;
        if (len2==0)
            return 0;
        int flag = 0;
        for (int i=0;i<len1-len2+1;i++)
        {
            for (int j=0;j<len2;j++)
                if (haystack[i+j]==needle[j])
                    flag = 1;
                else
                {
                    flag = 0;
                    break;
                }
            if (flag == 1)
                return i;
        }
        return -1;
    }
};

python3源代码:

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        len1 = len(haystack)
        len2 = len(needle)
        if len1<len2:
            return -1
        if len2==0:
            return 0
        flag = 0
        for i in range(len1-len2+1):
            for j in range(len2):
                if haystack[i+j]==needle[j]:
                    flag = 1
                else:
                    flag = 0
                    break
            if flag == 1:
                return i
        return -1

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83477881