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