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).