Skip to content

Latest commit

 

History

History
54 lines (38 loc) · 1.04 KB

File metadata and controls

54 lines (38 loc) · 1.04 KB

KMP Algorithm

Problem Link

https://leetcode.com/problems/implement-strstr/


Pattern

  • String
  • Pattern Matching

Approach

Build failure function (LPS array) to handle mismatches efficiently without restarting.


Time Complexity

O(n + m)

Space Complexity

O(m)


Java Solution

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle.length() == 0) return 0;
        int[] lps = new int[needle.length()];
        for (int i = 1; i < needle.length(); i++) {
            int j = lps[i - 1];
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) j = lps[j - 1];
            if (needle.charAt(i) == needle.charAt(j)) j++;
            lps[i] = j;
        }
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = lps[j - 1];
            if (haystack.charAt(i) == needle.charAt(j)) j++;
            if (j == needle.length()) return i - j + 1;
        }
        return -1;
    }
}