问题描述:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
解题思路:
遍历方法,时间复杂度为O(n)。首先从字符串的开头位置一直往后遍历,在每次遍历的过程中由该位置向两边扩散,直到找到最长的子回文串为止。同时需要考虑奇字符串和偶字符串的情况。
代码如下:
1 public class Solution { 2 public String longestPalindrome(String s) { 3 int n = s.length(); 4 String longest = s.substring(0, 1); 5 6 if (s == null || s.length() == 0) 7 return null; 8 for (int i = 0; i < n; i++) { 9 String p1 = expandFromCenter(s, i, i); 10 if (p1.length() > longest.length()) 11 longest = p1; 12 String p2 = expandFromCenter(s, i, i + 1); 13 if (p2.length() > longest.length()) 14 longest = p2; 15 } 16 return longest; 17 } 18 19 public String expandFromCenter(String s, int c1, int c2) { 20 int head = c1; 21 int tail = c2; 22 int m = s.length(); 23 24 while (head >= 0 && tail < m && s.charAt(head) == s.charAt(tail)) { 25 head--; 26 tail++; 27 } 28 return s.substring(head + 1, tail); 29 } 30 }
时间: 2024-10-08 03:05:51