Find the Index of the First Occurrence in a String
LeetCode 28 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Check every start position until one fully matches.
আমি 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
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.
আমি কীভাবে সমাধান করেছি
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 -1Find 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).