Advertisement
1988coder

5. Longest Palindromic Substring

Jan 2nd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. /**
  2.  * Expand around center. Helper function returns the length of the palindrome.
  3.  *
  4.  * Time Complexity: O(N^2)
  5.  *
  6.  * Space Complexity: O(1)
  7.  *
  8.  * N = Length of the input string s.
  9.  */
  10. class Solution {
  11.     public String longestPalindrome(String s) {
  12.         if (s == null) {
  13.             return "";
  14.         }
  15.         if (s.length() < 2) {
  16.             return s;
  17.         }
  18.         int start = 0;
  19.         int maxLen = 0;
  20.         for (int i = 0; i < s.length() - 1; i++) {
  21.             int len1 = extendPalindrome(s, i, i);
  22.             int len2 = extendPalindrome(s, i, i + 1);
  23.             if (maxLen < Math.max(len1, len2)) {
  24.                 start = len1 > len2 ? (i - len1 / 2) : (i - len2 / 2 + 1);
  25.                 maxLen = Math.max(len1, len2);
  26.             }
  27.         }
  28.  
  29.         return s.substring(start, start + maxLen);
  30.     }
  31.  
  32.     private int extendPalindrome(String s, int left, int right) {
  33.         while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
  34.             left--;
  35.             right++;
  36.         }
  37.         return right - (left + 1);
  38.     }
  39. }
  40.  
  41. /**
  42.  * Expand around center. Helper function returns the length of the palindrome.
  43.  *
  44.  * Time Complexity: O(N^2)
  45.  *
  46.  * Space Complexity: O(N)
  47.  *
  48.  * N = Length of the input string s.
  49.  */
  50. class Solution {
  51.     public String longestPalindrome(String s) {
  52.         if (s == null) {
  53.             return "";
  54.         }
  55.         if (s.length() < 2) {
  56.             return s;
  57.         }
  58.  
  59.         String max = "";
  60.         for (int i = 0; i < s.length() - 1; i++) {
  61.             String s1 = extendPalindrome(s, i, i);
  62.             String s2 = extendPalindrome(s, i, i + 1);
  63.             if (s1.length() > max.length()) {
  64.                 max = s1;
  65.             }
  66.             if (s2.length() > max.length()) {
  67.                 max = s2;
  68.             }
  69.         }
  70.  
  71.         return max;
  72.     }
  73.  
  74.     private String extendPalindrome(String s, int left, int right) {
  75.         while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
  76.             left--;
  77.             right++;
  78.         }
  79.         return s.substring(left + 1, right);
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement