Member-only story
Repeated Substring Pattern: Leetcode tough KMP and Robin Karp Algorithm — Hackrank TOP 20
https://leetcode.com/problems/repeated-substring-pattern/
Easy But tough for me as I do not know two of the algorithm
1. Knuth-Morris-Pratt Algorithm and
2. Divisors + Rabin-Karp
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
Solution:
My intuition: We use the last character of the string. This last character is also the last character of the substring which we suspect is being repeated. So we search for this last character from the front of the string. When we find it, we use the substring from 0 to that index as the substring that we suspect ( “sups”). Then we loop the string to ensure the rest of the string is composed of only suspected string.
class Solution…