Advertisement
sanya5791

Longest Palindrome

Jul 2nd, 2021
1,769
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.81 KB | None | 0 0
  1. class Solution {
  2.     fun longestPalindrome(s: String): String {
  3.         if (s.length < 1){
  4.             return "";
  5.         }
  6.         var start = 0;
  7.         var end = 0;
  8.         for (i in 0..s.length - 1){
  9.             val len1 = expandAroundCenter(s, i, i);
  10.             val len2 = expandAroundCenter(s, i, i+1);
  11.             val len = Math.max(len1, len2);
  12.             if (len > (end - start)){
  13.                 start = i - (len - 1)/2;
  14.                 end = i + len / 2;
  15.             }
  16.         }
  17.         return s.substring(start, end + 1);
  18.     }
  19.    
  20.     fun expandAroundCenter(s: String, left: Int, right: Int): Int {
  21.         var L = left;
  22.         var R = right;
  23.         while (L >= 0 && R < s.length && s[L] == s[R]){
  24.             L--;
  25.             R++;
  26.         }
  27.        
  28.         return R-L -1;
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement