Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8858165

Browse files
Create LPS_O(n)
1 parent 9ef5eba commit 8858165

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎Algorithms/LPS_O(n)‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//Returns Longest Palindrome Subsequence length.
2+
//Time Complexity O(n).
3+
int LPSManchers(string input) {
4+
char forOddPalindrome = '-';
5+
//Uncomment the next line for odd length palindromes only.
6+
//forOddPalindrome = '$';
7+
8+
string newInput = "$";
9+
for(int i = 0; i < input.length(); i++) {
10+
newInput += input[i];
11+
newInput += '$';
12+
}
13+
input = newInput;
14+
15+
int length = input.length();
16+
int T[length];
17+
for(int i = 0; i < length; i++) {
18+
T[i] = 0;
19+
}
20+
int start = 0;
21+
int end = 0;
22+
for(int i = 0; i < length; ) {
23+
while((start > 0) && (end < length - 1) && (input[start-1] == input[end+1])) {
24+
start--;
25+
end++;
26+
}
27+
T[i] = end - start + 1;
28+
if(end == length - 1) {
29+
break;
30+
}
31+
int newCenter = end + (i%2 == 0 ? 1 : 0);
32+
for(int j = i + 1; j <= end; j++) {
33+
T[j] = min(T[i - (j - i)], 2 * (end - j) + 1);
34+
if(j + T[i - (j - i)]/2 == end) {
35+
newCenter = j;
36+
break;
37+
}
38+
}
39+
i = newCenter;
40+
end = i + T[i]/2;
41+
start = i - T[i]/2;
42+
}
43+
int max = INT_MIN;
44+
for(int i = 0; i < length; i++) {
45+
if(input[i] != forOddPalindrome) {
46+
int val;
47+
val = T[i]/2;
48+
if(max < val) {
49+
max = val;
50+
}
51+
}
52+
}
53+
return max;
54+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /