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