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,大于则继续搜索,否则提前结束搜索。


public class Solution {
public int isPalindrome(String s,int start,int end){
        int low = start;
		int high = end;
		while(start < end){
    		if(s.charAt(start ++) != s.charAt(end --))
    			return -1;
		}
		return high - low + 1;
	}
	
	public String longestPalindrome(String s) {
		int max = 1;
		int low=0,high=0;
		for(int i = 0 ; i < s.length() - max ; i++){
			for(int j= s.length() -1 ; j -i +1 > max ; j--){
				if(isPalindrome(s, i, j) > max){
					max = isPalindrome(s, i, j);
					low = i;
					high = j;
				}
			}
		}
		return s.substring(low, high+1);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值