码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode 5. Longest Palindromic Substring

时间:2019-05-23 20:55:16      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:turn   leetcode   har   span   als   else   n+1   一个   substr   

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"

 1 class Solution {
 2     public boolean isPalindromic(String s, int begin, int end) {
 3         if (begin == end)
 4             return true;
 5         for (int i = 0; i <= (end - begin) / 2; i++) {
 6             if (s.charAt(begin + i) != s.charAt(end - i))
 7                 return false;
 8         }
 9         return true;
10     }
11 
12     public String longestPalindrome(String s) {
13         if (s.length() <= 1) return s;
14         int[] res = new int[s.length()];// 存放以当前位置结束的最长回文子串的长度
15 
16         res[0] = 1;
17         for (int i = 1; i < s.length(); i++) {
18             int begin = i - res[i - 1] - 1;//以i-1位置结尾的最长回文子串的开始位置的前一个位置
19             if (begin < 0) {
20                 /*
21                  * 查找以i结尾的最长回文子串
22                  * */
23                 for (int j = 0; j <= i; j++) {
24                     if (isPalindromic(s, j, i)) {
25                         res[i] = i - j + 1;
26                         break;
27                     }
28                 }
29             } else {
30                 if (s.charAt(begin) == s.charAt(i)) {
31                     res[i] = res[i - 1] + 2;
32                 } else {
33                     // 判断begin+1到i子串是否是回文子串
34                     for (int j = 0; j <= i; j++) {
35                         if (isPalindromic(s, j, i)) {
36                             res[i] = i - j + 1;
37                             break;
38                         }
39                     }
40                 }
41             }
42         }
43         int max = 0;
44         for (int i = 0; i < s.length(); i++) {
45             if (res[max] < res[i]) max = i;
46         }
47         return s.substring(max - res[max] + 1, max + 1);
48     }
49 }

 

leetCode 5. Longest Palindromic Substring

标签:turn   leetcode   har   span   als   else   n+1   一个   substr   

原文地址:https://www.cnblogs.com/yfs123456/p/10914311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!