Advertisement
1988coder

214. Shortest Palindrome

Jan 4th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. /**
  2.  * KMP(Knuth–Morris–Pratt) String-Search Algorithm (Only create the lookup
  3.  * table)
  4.  *
  5.  * We add "#" here to force the match in reverse(s) starts from its first index.
  6.  * What we do in KMP here is trying to find a match between prefix in s and a
  7.  * postfix in reverse(s). The match part will be palindrome substring.
  8.  *
  9.  * Time Complexity: O(N)
  10.  *
  11.  * Space Complexity: O(N)
  12.  *
  13.  * N = Length of the input string
  14.  */
  15. class Solution1 {
  16.     public String shortestPalindrome(String s) {
  17.         if (s == null) {
  18.             return "";
  19.         }
  20.         if (s.length() < 2) {
  21.             return s;
  22.         }
  23.         String reverseStr = new StringBuilder(s).reverse().toString();
  24.         String tempStr = s + "#" + reverseStr;
  25.  
  26.         int[] table = getKmpLookupTable(tempStr);
  27.  
  28.         String strToBeAdded = new StringBuilder(s.substring(table[table.length - 1])).reverse().toString();
  29.  
  30.         return strToBeAdded + s;
  31.     }
  32.  
  33.     private int[] getKmpLookupTable(String s) {
  34.         int[] lookupTable = new int[s.length()];
  35.         int index = 0;
  36.         int i = 1;
  37.         while (i < s.length()) {
  38.             if (s.charAt(i) == s.charAt(index)) {
  39.                 lookupTable[i] = index + 1;
  40.                 index++;
  41.                 i++;
  42.             } else {
  43.                 if (index > 0) {
  44.                     index = lookupTable[index - 1];
  45.                 } else {
  46.                     i++;
  47.                 }
  48.             }
  49.         }
  50.         return lookupTable;
  51.     }
  52. }
  53.  
  54. /*
  55.  * Two-Pointers and Recursion
  56.  *
  57.  * Time Complexity: O(n^2) Space Complexity: O(n)
  58.  */
  59. class Solution2 {
  60.     public String shortestPalindrome(String s) {
  61.         if (s == null) {
  62.             return "";
  63.         }
  64.         if (s.length() < 2) {
  65.             return s;
  66.         }
  67.  
  68.         int j = 0;
  69.         for (int i = s.length() - 1; i >= 0; i--) {
  70.             if (s.charAt(i) == s.charAt(j)) {
  71.                 j++;
  72.             }
  73.         }
  74.         if (j == s.length()) {
  75.             return s;
  76.         }
  77.  
  78.         String suffix = s.substring(j);
  79.         String suffixRev = new StringBuilder(suffix).reverse().toString();
  80.  
  81.         return suffixRev + shortestPalindrome(s.substring(0, j)) + suffix;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement