28 leetcode - Implement strStr()

来源:互联网 发布:大数据上市公司有哪些 编辑:程序博客网 时间:2024/06/05 02:58
#!/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 -1if __name__ == "__main__":    s = Solution()    print s.strStr('abc','bcd')
0 0
原创粉丝点击