Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Show Similar Problems
python string is immutable .. have to do sth not optimized. may change it in the future.
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if haystack == "" and needle == "":
return 0
if haystack == "" and needle != "":
return -1
if needle == "":
return 0
newstr = haystack.split(needle)
if len(newstr[0]) == len(haystack):
return -1
return len(newstr[0])
实现strStr():寻找字符串中的子串

本文介绍如何实现strStr()函数,用于在主字符串中查找子字符串的首次出现位置,若未找到则返回-1。通过实例演示和代码解析,深入理解字符串操作与算法应用。

被折叠的 条评论
为什么被折叠?



