LeetCode : Longest Palindromic Substring [java]

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.(

思路:把字符串字符间的间隙考虑进去,即回文可能从某个字符向两侧寻找,也可能从一个间隙向两侧寻找,字符个数加上间隙个数一共需要查找 n + (n -1) 次,n为字符串长度。

            每次都从中心向两侧查找(最笨的方法了吧!哈哈!)


public class Solution {
    public String longestPalindrome(String s) {
        int length = s.length();
		int leftIndex;
		int rightIndex;
		String result = "";
		for (int i = 0; i < 2 * length - 1; i++) {
			if (i % 2 == 0) {
				leftIndex = i / 2;
				rightIndex = i / 2;
			} else {
				leftIndex = i / 2;
				rightIndex = i / 2 + 1;
			}
			String palindrome = getPalindrome(s, leftIndex, rightIndex);
			result = palindrome.length() > result.length() ? palindrome : result;
		}
		return result;
	}

	public String getPalindrome(String s, int leftIndex, int rightIndex) {
		while (leftIndex >= 0 && rightIndex < s.length() && s.charAt(leftIndex) == s.charAt(rightIndex)) {
			leftIndex--;
			rightIndex++;
		}
		return s.substring(leftIndex + 1, rightIndex);
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值