|
| 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