Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 28 · String Matching (KMP / Rabin-Karp)

Find the Index of the First Occurrence in a String

LeetCode 28 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Check every start position until one fully matches.

எளிதுTwo PointersStringString MatchingZ AlgorithmKnuth–Morris–Pratt Algorithm
LeetCode இல் திற ↗

நான் Find the Index of the First Occurrence in a String (LeetCode 28) ஐ இப்படித் தீர்த்தேன் — String Matching (KMP / Rabin-Karp) பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Slide a window of the needle's length across the haystack and compare character by character; the first full match gives the answer.

Approach

  1. 1

    For each start up to n − m.

  2. 2

    Compare needle[i] against haystack[start + i]; break on mismatch.

  3. 3

    If the last character matched, return start.

நான் எப்படித் தீர்த்தேன்

Brute-force windowPythonO(n·m) time · O(1) space
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n=len(haystack)
        m = len(needle)
        window_start=0
        while window_start<n-m+1:
            for i in range(m):
                if haystack[window_start+i]!=needle[i]:
                    break
                if i==m-1:
                    return window_start
            window_start=window_start+1
        return -1
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Find the Index of the First Occurrence in a String — அடிக்கடி கேட்கப்படும் கேள்விகள்

Find the Index of the First Occurrence in a String பின்னாலுள்ள intuition என்ன?

Slide a window of the needle's length across the haystack and compare character by character; the first full match gives the answer.

Find the Index of the First Occurrence in a String (LeetCode 28) ஐ எப்படித் தீர்ப்பது?

1. For each start up to n − m. 2. Compare needle[i] against haystack[start + i]; break on mismatch. 3. If the last character matched, return start.

Find the Index of the First Occurrence in a String இன் time மற்றும் space complexity என்ன?

Time: O(n · m). Space: O(1). (Accepted approach: Brute-force window.)

Find the Index of the First Occurrence in a String இல் பொதுவான தவறுகள் என்ன?

KMP brings this down to O(n + m).