From 3d95f73a40e713338d207067d72d8c3244f6c397 Mon Sep 17 00:00:00 2001 From: Srajika gupta <32300828+srajika256@users.noreply.github.com> Date: Sat, 31 Oct 2020 15:42:01 +0530 Subject: [PATCH] Create 28 - Implement strstr Implement str str using KMP algorithm better than 100% of the solutions --- LeetCode/28 - Implement strstr | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 LeetCode/28 - Implement strstr diff --git a/LeetCode/28 - Implement strstr b/LeetCode/28 - Implement strstr new file mode 100644 index 0000000..5b0c1c1 --- /dev/null +++ b/LeetCode/28 - Implement strstr @@ -0,0 +1,62 @@ +class Solution { + + vector LPS(string s) +{ + int n = s.length(); + vector lps(n); + lps[0] = 0; + int j = 0; + + for (int i = 1; i < n; i++) + { + if (s[i] == s[j]) + { + lps[i] = ++j; + } + else + { + while (j > 0 && s[i] != s[j]) + j = lps[j - 1]; + if (s[i] == s[j]) + lps[i] = ++j; + else + {lps[i] = 0;} + } + } + return lps; +} + +public: + int strStr(string s, string p) { + if(p.length() == 0) + {return 0;} + + if(s.length() lps = LPS(p); + + while (i < s.length() && j < p.length()) + { + if (s[i] == p[j]) + {i++; j++;} + else + { + if(j!=0) + {j = lps[j - 1];} + else + {i++;} + } + } + + if (j == p.length()) + return (i - p.length()); + + return -1; + } +};