admin管理员组文章数量:1636978
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/linhuanmars/article/details/20276833
提出了一种rolling hash的方式。
本文标签: implementLeetCodePythonstrStr
版权声明:本文标题:Leetcode-Implement strStr()-Python 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729234570a1191847.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论