LeetCode之实现 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() 定义相符。

二、解题思路

2.1 方法一:效率低

类似滑窗比较

func strStr(haystack string, needle string) int {
// 先判断needle是否为空
if needle == "" {
return 0
}
// 接着判断needle的长度是否超过haystack的长度
if len(haystack) < len(needle) {
return -1
}
for i := 0; i < len(haystack); i++ {
// 记录当前的位置
index := i
for j := 0; j < len(needle); j++ {
// 保证index值不能超过haystack的值,
if index < len(haystack) && haystack[index] == needle[j] {
if j == len(needle) - 1 {
return i
} else {
index++
}
} else {
break
}
}
}
return -1
}
2.2 方法二:最简单

直接利用切割子串比较,控制下边界值就可以了!
执行时间是0,内存占是2.2m!

func strStr(haystack string, needle string) int {
if needle == "" {
return 0
}
if len(haystack) < len(needle) {
return -1
}
for i := 0; i < len(haystack); i++ {
// 获取截取的end位置
next := i + len(needle)
// 保证next的值不能操作haystack的长度
if next > len(haystack) {
return -1
}
if haystack[i:next] == needle {
return i
}
}
return -1
}

三、链接

题目链接:https://leetcode-cn.com/problems/implement-strstr/

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。