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