您的位置:首页 > 编程语言 > Python开发

Leetcode-Implement strStr()-Python

2017-08-17 19:39 621 查看

Implement strStr()

从字符串中找出给定子字符串的索引,若不存在则返回-1。

Description

解题思路

用python解决这道题很简单,因为python字符串自带的find的方法可以直接实现。

def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)


不采用find()方法的解题思路

采用brute force方式,即依次从字符串的每个位置开始,截取和子字符串相同长度的字符串,与给定的子字符串进行比较。

def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1


改进:http://blog.csdn.net/linhuanmars/article/details/20276833

提出了一种rolling hash的方式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息