代码随想录算法训练营第九天| 28. 实现 strStr()、459.重复的子字符串

97 阅读1分钟

Leetcode 28 Find the Index of the First Occurrence in a String

1. 第一想法

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(haystack)
        m = len(needle)
        start = n-m
        if start == 0:
            if haystack == needle:
                return 0
        for i in range(start + 1):
            p1 = i
            p2 = 0
            while haystack[p1] == needle[p2]:
                p1 += 1
                p2 += 1
                if p2 == len(needle):
                    return i

        return -1

2. 看完后想法

class Solution:
    def getNext(self, next: list[int], s: str) -> None:
        j = 0
        next[0] = 0
        for i in range(1, len(s)):
            while j > 0 and s[i] != s[j]:
                j = next[j-1]
            if s[i] == s[j]:
                j += 1
            next[i] = j
    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle) == 0:
            return 0
        next = [0] * len(needle)
        self.getNext(next, needle)
        j = 0
        for i in range(len(haystack)):
            while j > 0 and haystack[i] != needle[j]:
                j = next[j-1]
            if haystack[i] == needle[j]:
                j += 1
            if j == len(needle):
                return i - len(needle) + 1
        return -1
        

3. 总结

常看常新。

Leetcode 459 Repeated Substring Pattern

1. 第一想法

怎么找 substring 呢。

2. 看完后想法

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        if len(s) == 0:
            return False
        nxt = [0] * len(s)
        self.getNext(nxt,s)
        if nxt[-1] != 0 and len(s) % (len(s) - nxt[-1]) == 0:
            return True
        return False
    
    def getNext(self, nxt, s):
        nxt[0] = 0
        j = 0
        for i in range(1, len(s)):
            while j > 0 and s[i] != s[j]:
                j = nxt[j-1]
            if s[i] == s[j]:
                j += 1
            nxt[i] = j
        return nxt

3. 总结

常看常新。