最长回文子串两种解法

刷leetcode...

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"

思路:遍历每一个字符,以字符为中心,将字符串对折,如果对应的字符相等,则可以确认该字符串为回文串。

下面是第一次的解法,在每个字符中间插入一个间隔符,如s="abb",插入间隔符之后变成str="a#b#b",插入间隔符之后不会影响原回文字符的顺序。

package Algorithms;

public class palindromic_substring5 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(longestPalindrome("abb"));

	}

	//耗时671ms
	public static String longestPalindrome(String s) {
		if(s != null && !s.equals("")) {
			String re = s.substring(0,1);
			String temps = s.substring(0,1);
			int max = 1;
			int temp = 1;
			
			String str = "";
			int length = 2*s.length() - 1;
			int count = 0;
			for(int i = 0;i < s.length();i ++) {
				str = str + s.charAt(i);
				if(count < length) {
					str = str + "#";
				}
			}
			
			for(int i = 0;i < length;i ++) {
				boolean isExist = true;
				int j = i - 1;
				int k = i + 1;
				
				while(j >= 0 && k < length && isExist) {
					if(str.charAt(j) != str.charAt(k)) {
						temps = str.substring(j + 1, k);
						isExist = false;
					}else {
						j --;
						k ++;
					}
				}
				
				if(temps.equals("")) {
					temps = str.substring(j+1, k);
				}
				temps = temps.replaceAll("#", "");
				temp = temps.length();
				if(temp > max) {
					re = temps;
					max = temp;
				}
				temps = "";
			}
			
			return re;
		}else {
			return s;
		}
	}
}

经过思考,将上述方法进行改进,不需要往字符串中插入间隔符

package Algorithms;

public class palindromic_substring5 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(longestPalindrome("abb"));

	}

	//耗时97ms
	public static String longestPalindrome(String s) {
		if(s != null && !s.equals("")) {
			String re = s.substring(0,1);
			String temps = "";
			int max = 1;
			int temp = 0;
			
			for(int i = 0;i < s.length();i ++) {
				boolean isExist = true;
				int j = i, k = i;
				
				while(j >= 0 && k < s.length() && isExist) {
					if(s.charAt(j) != s.charAt(k)) {
						temps = s.substring(j + 1, k);
						isExist = false;
					} else {
						if((k+1) < s.length() && (j-1) >= 0 && s.charAt(j-1) == s.charAt(k+1)) {
							//continue;
						}else if((k+1) < s.length() && s.charAt(j) == s.charAt(k+1)) {
							if(isPalindromicSubstring(s.substring(j,k+2))) {
								j ++;
							}
						}
						j --;
						k ++;
					}
				}
				
				if(temps.equals("")) {
					temps = s.substring(j+1, k);
				}
				temp = temps.length();
				if(temp > max) {
					re = temps;
					max = temp;
				}
				temps = "";
				
				if(k >= s.length()) {
					break;
				}
			}
			return re;
		}else {
			return s;
		}
	}

        //判断是否为回文串
	public static boolean isPalindromicSubstring(String s) {
		
		if(s.length() == 1) {
			return true;
		}
		char[] ch = s.toCharArray();
		for(int i = 0;i < ch.length/2; i++) {
			if(s.charAt(i) != ch[ch.length - 1 - i]) {
				return false;
			}
		}
		
		return true;
	}
}

变快了很多。

看提交记录中的耗时分布图,最快的居然只用了6ms,而且耗时在20-30ms内的解法还很多,感慨一句自己真是很辣鸡啊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用中的代码展示了一种求解最长回文子串的暴力解法,即遍历字符串的所有子串,判断是否为回文,并记录最长的回文子串。但是这种方法的时间复杂度较高,不适用于较长的字符串。 Python 中有一种更优化的方法来求解最长回文子串,即中心扩展法。该方法的基本思想是从字符串的每个字符和每两个相邻字符之间展开,向两边扩展判断是否为回文子串。具体步骤如下: 1. 定义一个函数 expandAroundCenter,用于判断以某个中心点向两边扩展的回文子串的长度。 2. 遍历字符串,将每个字符和其相邻字符都作为中心点进行扩展,计算得到回文子串的最大长度。 3. 根据最大长度和中心点位置,确定最长回文子串的起始位置和结束位置。 4. 返回最长回文子串。 下面是基于中心扩展法的 Python 代码示例: ``` class Solution: def longestPalindrome(self, s): if len(s) < 2: return s start, end = 0, 0 for i in range(len(s)): len1 = self.expandAroundCenter(s, i, i) # 以一个字符为中心向两边扩展 len2 = self.expandAroundCenter(s, i, i+1) # 以相邻两个字符为中心向两边扩展 max_len = max(len1, len2) if max_len > end - start: start = i - (max_len - 1) // 2 end = i + max_len // 2 return s[start:end+1] def expandAroundCenter(self, s, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return right - left - 1 s = "ac" S = Solution() result = S.longestPalindrome(s) print(result) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值