-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLongestPrefixSuffix.java
51 lines (49 loc) · 1.24 KB
/
LongestPrefixSuffix.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*https://practice.geeksforgeeks.org/problems/longest-prefix-suffix2527/1*/
/*https://leetcode.com/problems/longest-happy-prefix/*/
class Solution {
int lps(String s) {
int n = s.length();
int[] dp = new int[n];
int i = 0, j = 1;
while (j < n)
{
if (s.charAt(i) == s.charAt(j))
{
dp[j] = i+1;
++j; ++i;
}
else
{
if (i == 0) ++j;
else if (i == 1)
{
i = 0;
dp[j] = 0;
}
else
{
dp[j] = 0;
j = j-i+1;
i = 0;
}
}
}
return dp[n-1];
}
}
class Solution {
public String longestPrefix(String s) {
int i = 1, lpsLen = 0, pLen = s.length();
int[] lps = new int[pLen];
char[] p = s.toCharArray();
while (i < pLen)
{
if (p[i] == p[lpsLen])
lps[i++] = ++lpsLen;
else if (lpsLen != 0)
lpsLen = lps[lpsLen-1];
else lps[i++] = lpsLen;
}
return s.substring(0,lps[pLen-1]);
}
}