Leetcode 实现 StrStr
Leetcode 实现 StrStr
Categories:
实现 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() 定义相符。
解题思路
如果查找字符串为空或者两个字符串相同,直接返回0
定义两个变量i=needle长度, k=haystack长度
从0到k-i+1遍历haystack, 以i长度截取字符串对比needle, 如果找到返回当前索引
找不到返回-1
Answer
1#
2# @lc app=leetcode.cn id=28 lang=python3
3#
4# [28] 实现 strStr()
5#
6
7# @lc code=start
8class Solution:
9 def strStr(self, haystack: str, needle: str) -> int:
10 if not needle or haystack == needle:
11 return 0
12 j = len(needle)
13 k = len(haystack)
14 for i in range(k-j+1):
15 if haystack[i:i+j] == needle:
16 return i
17 return -1
18# @lc code=end
Accepted
74/74 cases passed (36 ms)
Your runtime beats 91.04 % of python3 submissions
Your memory usage beats 6.67 % of python3 submissions (13.5 MB)