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