LeetCode算法5:最长回文字符串

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

示例 1:
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。

示例 2:
输入: “cbbd”
输出: “bb”

问题评价
最重要在于判别函数的引入,可以简化程序的结构;

解题思路

边界问题

1、对于空字符串,进行字符串截取时,需要个别化排除边界问题;

代码

public class _05LongestPalindromicSubstring {

	public String longestPalindrome(String s) {

		int lenght = s.length();
		int start = 0;
		int end = 0;

		if(lenght==0) return "";
		
		for (int i = 0; i < lenght; i++) {
			for (int j = i; j < lenght; j++) {
				String teststr = s.substring(i, j+1);
				if (isPalindrome(teststr)) {
					if ((j - i) > (end - start)) {
						start = i;
						end = j;
					}
				}
			}
		}
		return s.substring(start, end+1);
	}

	public Boolean isPalindrome(String s) {

		int lenght = s.length();

		Boolean isPalindrome = true;

		for (int i = 0; i < lenght / 2; i++) {
			if (s.charAt(i) != s.charAt(lenght - i - 1)) {
				isPalindrome = false;
				break;
			} else {
				isPalindrome = true;
				continue;
			}
		}
		return isPalindrome;
	}

	public static void main(String[] args) {

		_05LongestPalindromicSubstring _05LongestPalindromicSubstring = new _05LongestPalindromicSubstring();

		String s = "a";

		String ss = _05LongestPalindromicSubstring.longestPalindrome(s);

		System.out.println(ss);

	}
	//对于较长的字符串,系统提示超时,因此需要考虑时间复杂度更低的方法;
}

猜你喜欢

转载自blog.csdn.net/xihuanyuye/article/details/99711142