【LeetCode系列】Leet Code OJ 28. Implement strStr() [Difficulty: Easy]

题目链接

这题用PYTHON写感觉就是在作弊,没什么意义,先贴一个作弊方法:

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle in haystack:
            return haystack.index(needle)
        else:
            return -1

但是还是正经地写一下吧

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) == 0: return 0
        if len(haystack) == 0: return -1
        if len(haystack) < len(needle): return -1
        st1 = 0
        st2 = 0
        point = 0
        while st1 < len(haystack):
            while st1<len(haystack) and haystack[st1] != needle[st2]  : st1 += 1
            if st1<len(haystack): point = st1
            else:  return -1
            
            if len(haystack) - st1 < len(needle): return -1
            while st2<len(needle) and st1<len(haystack) and haystack[st1] == needle[st2] :
                st1 += 1
                st2 += 1
            if st2 == len(needle): return point
            else:
                st1 = point+1
                st2 = 0

        return -1

这样子的话勉强还是能过关的,没有使用KMP,就字符一个个匹配。。虽然这是水题,不过确实也是有很多小细节都要注意的。

猜你喜欢

转载自blog.csdn.net/u013379032/article/details/81227003