LeetCode 5 Longest Palindromic Substring

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.

 

思路:这道题采用遍历法,分两种情况考虑;

1.ada类型

2.aadd类型

对于上述两种类型,分别以k、k+1索引 或者k、k+2索引来判断,然后设置两个标记 i、j 索引,分别向两边计数,当出现j-i有最大值时,返回该索引。

代码如下:

 
public class Solution {
    public String longestPalindrome(String s) {
    	int length =s.length();
    	int max1=0,max2=0;//记录两个索引
    	int len = 0;
    	if(length == 2 && s.charAt(0)==s.charAt(1)||length ==1){
         return s;
    	}
    	for (int k = 0; k < length-1; k++) {
		if(s.charAt(k)==s.charAt(k+1)){
			if(len<=1){
			max1 = k;
			max2 =k+1;
			len = 1;
			}
			int i = k-1;
			int j = k+2;
			while(i>=0&&j<=length-1){
				if(s.charAt(i)==s.charAt(j)){
					if(j-i>len){
						max1 = i;
						max2 = j;
						len = max2 - max1;
					}
					i--;
					j++;
			}else{
				break;
				}
		}
		}
		if(k+2>=length){
			continue;
		}
		if (s.charAt(k)==s.charAt(k+2)) {
			if(len<=2){
				max1 = k;
				max2 =k+2;
				len = 2;
				}
			int i = k-1;
			int j = k+3;
			while(i>=0&&j<=length-1){
				if(s.charAt(i)==s.charAt(j)){
					if(j-i>len){
						max1 = i;
						max2 = j;
						len = max2 - max1;
					}
					i--;
					j++;
			}else{
				break;
				}
			}
		}			
		}
		return s.substring(max1, max2+1);
    }
}
这里有个优化算法,值得一看

http://www.cnblogs.com/bitzhuwei/p/Longest-Palindromic-Substring-Part-II.html

你可能感兴趣的:(LeetCode 5 Longest Palindromic Substring)