#!/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')
28 leetcode - Implement strStr()
最新推荐文章于 2025-08-16 00:47:01 发布