5. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

 Example:

Input: "cbbd"

Output: "bb"
题目含义:查找最长的回文子串
 1 class Solution {
 2    private int low, maxLen;
 3 
 4     private void huiwen(String s, int i, int j) {
 5         while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {
 6             i--;
 7             j++;
 8         }
 9         if (maxLen < j - i - 1) {
10             low = i + 1;
11             maxLen = j - i - 1;
12         }
13     }
14     public String longestPalindrome(String s) {
15         if (s.length() < 2) return s;
16         for (int i = 0; i < s.length()-1; i++) {
17             huiwen(s, i, i);
18             huiwen(s, i, i + 1);
19         }
20         return s.substring(low, low+maxLen);  
21     }
22 }

 



posted @ 2017-10-17 16:38  daniel456  阅读(138)  评论(0编辑  收藏  举报