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 }        

 

转载于:https://www.cnblogs.com/hbpeng/p/4788945.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值