Posts Longest Prefix Suffix
Post
Cancel

Longest Prefix Suffix

Problem Description

Given a string of characters, find the length of the longest proper prefix which is also a proper suffix. NOTE: Prefix and suffix can be overlapping but they should not be equal to the entire string.
geeksforgeeks

Example:
Input: s = “abab”
Output: 2
Explanation: “ab” is the longest proper
prefix and suffix.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    
    int lps(String s) {
        
        int[] lps = new int[s.length()];
        lps[0] = 0;
        int maxLength = 0;
        
        for(int i=1; i<s.length(); i++){
            
            int x = lps[i-1];
            while(s.charAt(i) != s.charAt(x)){
                if(x == 0){
                    x=-1;
                    break;
                }
                x = lps[x-1];
            }
            
            lps[i] = x+1;
            if(lps[i] > maxLength) maxLength = lps[i];
            
        }
        
        return lps[s.length()-1];
        
    }
}
This post is licensed under CC BY 4.0 by the author.