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

28 leetcode - Implement strStr()

2016-11-30 20:43 513 查看
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
中文:字符串a和b,返回b在a的位置,如果a不包含b返回-1
'''
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len_haystack,len_needle = len(haystack),len(needle)

if len_needle == 0:  #needle为空
return 0

if len_needle > len_haystack: #needle长度大于haystack,肯定匹配不上
return -1

i = 0
while i < len_haystack - len_needle + 1:  #比较的字符串长度需要大于等于needle,比needle还短的话没必要比较
j = 0
flag = True
while j < len_needle:
if haystack[i + j] != needle[j]:
flag = False
break
j += 1

if flag == True:
return i
i += 1

return -1

if __name__ == "__main__":
s = Solution()
print s.strStr('abc','bcd')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息