本文共 637 字,大约阅读时间需要 2 分钟。
要实现strStr()函数,我们可以利用Python的内置字符串方法来高效地解决问题。以下是详细的解决方案和代码实现。
我们需要在haystack中查找needle的第一个出现位置。具体步骤如下:
这种方法利用了Python字符串的高效查找功能,时间复杂度为O(n),其中n是haystack的长度,适用于大型数据。
class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 try: return haystack.index(needle) except ValueError: return -1
这种方法简洁高效,处理了所有情况,包括针为空和未找到情况。
转载地址:http://ifog.baihongyu.com/