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

这道题嘛,解出来也不难,当然不是最优。  从第二个字符开始判断是不是回文后半段的第一个字符,分成奇数和偶数两种情况。


public class Solution {
    public String longestPalindrome(String s) {
        char[] ch = s.toCharArray();
        if(ch.length == 1)
        	return s;
        int count = 0;
        int maxnum = 0;
        int maxindex = 0;
        int temple = 0;
        int tempri = 0;
        boolean flag = false;
        String str = "";
        for(int i = 1; i<ch.length - maxnum/2; i++){
        	if(ch[i] == ch[i-1]){
        		temple = i-2;
        		tempri = i+1;
        		count = 2;
        		while(temple>=0 && tempri<ch.length && ch[temple] == ch[tempri]){
        			count = count + 2;
        			temple--;
        			tempri++;
        		}
        		if(count > maxnum){
        			maxnum = count;
        			maxindex = i;
        			flag = false;
        		}
        		
        		
        	}
        	if(i+1<ch.length && ch[i+1] == ch[i-1]){
        		temple = i-2;
        		tempri = i+2;
        		count = 3;
        		while(temple>=0 && tempri<ch.length && ch[temple] == ch[tempri]){
        			count = count + 2;
        			temple--;
        			tempri++;
        		}
        		if(count > maxnum){
        			maxnum = count;
        			maxindex = i;
        			flag = true;
        		}
        	}
        	
        }
        if(flag)
        	for(int j = (maxindex-maxnum/2);j<=maxindex+maxnum/2;j++)
        		str += ch[j];
        else
        	for(int j = (maxindex-maxnum/2);j<maxindex+maxnum/2;j++)
        		str += ch[j];
        return str;
    }
}


运行时间还凑合吧,击败了百分之五十的人。。。


LeetCode-5. Longest Palindromic Substring_第1张图片



这篇文章里介绍的挺好的,第四种方法没怎么看懂 点击打开链接



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