LeetCode:5. Longest Palindromic Substring(Medium)

原题链接:https://leetcode.com/problems/longest-palindromic-substring/description/

1. 题目要求:找出字符串中的最大回文子串

2. 注意:要考虑回文子串中的字符个数是奇数还是偶数!!!

例如,“aabaa”是一个奇数个字符的回文字符串,他的中心只有一个字符“b”。

“aabbaa”是一个偶数个字符的回文字符串,他的中心却有两个相同字符“bb”

3. 思路:暴力解决,以每个字符为中心,对该字符的两边进行匹配,找出最长的回文子串1;再以两个相邻字符为中心,进行同样操作,找出最长回文子串2。然后对两个子串进行比较,取最长者。

 1 class Solution {
 2     public String longestPalindrome(String s) {
 3     int start = 0, end = 0;
 4     for (int i = 0; i < s.length(); i++) {
 5         int len1 = expandAroundCenter(s, i, i);
 6         int len2 = expandAroundCenter(s, i, i + 1);
 7         int len = Math.max(len1, len2);
 8         if (len > end - start) {
 9             start = i - (len - 1) / 2;
10             end = i + len / 2;
11         }
12     }
13     return s.substring(start, end + 1);
14 }
15 
16 private int expandAroundCenter(String s, int left, int right) {
17     int L = left, R = right;
18     while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
19         L--;
20         R++;
21     }
22     return R - L - 1;
23 }
24 }
原文地址:https://www.cnblogs.com/huiAlex/p/8034451.html