Given a string of character, find the length of longest proper prefix which is also a proper suffix
belongs to collection: interview C++ coding problems/challenges | Implementation
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
belongs to collection: interview C++ coding problems/challenges | Implementation
total answers (1)
1) Brute Force Approach
Since the longest proper prefix which is also a suffix cannot be equal to the entire length of the string because it can't overlap each other, so we break the string from mid-point and start matching left and right string. If they are equal return size of any one string else try for shorter lengths on both sides.
Pseudo Code:
C++ Implementation:
Output
2) Better approach: Using longest prefix-suffix array of KMP algorithm
Here we will use an array which represents the length of the longest proper prefix which is also equal to the suffix of the array.
Here we use lps[] array which stores the length of a longest proper prefix which is the equal suffix, each index of lps represent the current index lps upto that index comparison, initialize lps[0]=0, since it is not possible to have proper prefix-suffix with one letter then we declare two variable j and i by which we compare the characters.
Pseudo Code:
C++ Implementation:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer