LeetCode_OJ【5】Longest Palindromic Substring

Given a string S, find the longest palindromic substring inS. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

这道题还是比较简单的,主要运用分支限界的方法,首先定义isPalindrome函数,如果是回文串就返回回文串的长度,否则返回-1.在搜索过程中不断比较当前搜索空间是否大于已经找出的最长串的长度max,大于则继续搜索,否则提前结束搜索。

 

 1 public class Solution {
 2   public int isPalindrome(String s,int start,int end){
 3      int low = start;
 4         int high = end;
 5         while(start < end){
 6             if(s.charAt(start ++) != s.charAt(end --))
 7                 return -1;
 8         }
 9         return high - low + 1;
10     }
11     
12     public String longestPalindrome(String s) {
13         int max = 1;
14         int low=0,high=0;
15         for(int i = 0 ; i < s.length() - max ; i++){
16             for(int j= s.length() -1 ; j -i +1 > max ; j--){
17                 if(isPalindrome(s, i, j) > max){
18                     max = isPalindrome(s, i, j);
19                     low = i;
20                     high = j;
21                 }
22             }
23         }
24         return s.substring(low, high+1);
25     }
26 }        

 

posted @ 2015-09-07 15:15  hbpeng  阅读(126)  评论(0)    收藏  举报