Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
Solution 1:
Time: O(N^2)
class Solution: def longestPalindrome(self, s: str) -> str: if len(s) <= 1: return s self.res = '' for i, char in enumerate(s): self.helper(i, i, s) # odd self.helper(i, i + 1, s) # even return self.res def helper(self, start, end, s, even=False): while start >= 0 and end < len(s): if s[start] == s[end]: if end - start >= len(self.res): self.res = s[start: end + 1] start -= 1 end += 1 else: return
class Solution { int start = 0; int maxLen = 0; public String longestPalindrome(String s) { int len = s.length(); for (int i = 0; i < len; i++) { helper(i, i, s); helper(i, i + 1, s); } return s.substring(start, start + maxLen); } private void helper(int low, int high, String s) { while (low >= 0 && high < s.length() && s.charAt(low) == s.charAt(high)) { low -= 1; high += 1; } if (high - low - 1 > maxLen) { maxLen = high - low - 1; start = low + 1; } } }
Solution 2:
Time: O(N^2)
class Solution { public String longestPalindrome(String s) { if (s == null || s.length() <= 1) { return s; } boolean[][] isPalin = new boolean[s.length()][s.length()]; int max = 0; String res = ""; for (int i = 1; i < s.length(); i++) { // i == j for case of single char for (int j = 0; j <= i; j++) { if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || isPalin[i - 1][j + 1])) { isPalin[i][j] = true; if (i - j + 1> max) { max = i - j + 1; // j is smaller than i res = s.substring(j, i + 1); } } } } return res; } }