LeetCode(java)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, and there exists one unique longest palindromic substring.

题目描述:找出一个字符串中的最长回文子串。

本人思路:

类似于网上所写的中心扩展法。从字符串中的每个位置开始向两边扩展,找到最长的回文。

时间复杂度:O(n²),leetcode通过时间:15ms。

public class Solution {
    	public static String longestPalindrome(String s) {
        char[] cs = s.toCharArray();
        int begin=0,end=0;
        int size = s.length();
        int out = 0;//中心位置
        
        for(int befor=out,after=out;out<size;out++)
        {
            //判断是否abcba类回文
        	for(;befor>0&&after<size-1;befor--,after++)
        	{
        		if(cs[befor-1] != cs[after+1])
        			break;
        	}
        	if(befor != after && after-befor>end-begin)
        	{
        			end=after;
        			begin=befor;
        	}
        	//判断是否abccba类回文
        	for(befor = out,after = out;befor>=0&&after<size-1;befor--,after++)
        	{
        		if(cs[befor] != cs[after+1])
        			break;
        	}
        	if(befor != after && after-(++befor)>end-begin)
        	{
        			end=after;
        			begin=befor;
        	}
        	//判断是否aaaaaa类回文
        	for(befor=out,after=out;after<size-1;after++)
        	{
        		if(cs[befor] != cs[after+1])
        			break;
        	}
        	if(after!=befor && after-befor>end-begin)
        	{
        			end=after;
        			begin=befor;
        			out = after;//跳过重复的序列
        	}
        }
        return s.substring(begin, end+1);
    }
}


除了这种解法还有以下几种解法:

①暴力解决法:遍历字符串中的每个子串,判断是否回文串,并更新最长回文串。

②动态规划:思想为:若 [ i , j ] 为回文,则 [ i+1, j-1 ]也为回文。

③Manacher's 算法。


附上大神制作的PPT(很详细):http://faculty.utpa.edu/liuy2/algorithmSlides/Longest-Palindromic-Substring.pptx


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值