Created
March 12, 2024 12:41
-
-
Save SuryaPratapK/e99a9b6c7ab51d910c8d729d6e1b200b to your computer and use it in GitHub Desktop.
KMP algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
void calculate_longestPrefixSuffix(string &needle,int m,vector<int>& lps){ | |
int l=0,r=1; | |
while(r<m){ | |
//If R-th char matches with L-th char | |
if(needle[l]==needle[r]){ | |
lps[r] = 1+l; | |
l++; | |
r++; | |
} else { | |
if(l>0) | |
l = lps[l-1]; | |
else | |
r++; | |
} | |
} | |
} | |
int patternMatcher(string& haystack,int n,string& needle,int m,vector<int>& lps){ | |
int haystack_pos=0; | |
int needle_pos=0; | |
while(needle_pos<m and haystack_pos<n){ | |
//If current char in pattern & text both match | |
if(haystack[haystack_pos]==needle[needle_pos]){ | |
haystack_pos++; | |
needle_pos++; | |
} | |
//Check if the pattern has been found | |
if(needle_pos==m) | |
return haystack_pos-m;//return starting pos of pattern | |
if(haystack[haystack_pos]!=needle[needle_pos]){ | |
if(needle_pos>0) | |
needle_pos = lps[needle_pos-1]; | |
else | |
haystack_pos++; | |
} | |
} | |
return -1; | |
} | |
public: | |
int strStr(string haystack, string needle) { | |
int n = haystack.size(); | |
int m = needle.size(); | |
if(m>n) | |
return -1; | |
vector<int> lps(m,0); //longest prefix suffix | |
calculate_longestPrefixSuffix(needle,m,lps); | |
return patternMatcher(haystack,n,needle,m,lps); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment