leedcode做题总结, 题目Longest Palindromic Substring 5

来源:互联网 发布:藏民对十一世班禅 知乎 编辑:程序博客网 时间:2024/05/01 01:46

题目是求一个字符串的最长回文子串,可以用两种方法,一种是动态规划,用一个矩阵,boolean[i,j] 表示字符串从i-j是否为一个回文串,我用的方法是直接判断,DP方法见http://www.cnblogs.com/dollarzhaole/archive/2013/07/22/3207364.html


class Solution11 {    public String longestPalindrome(String input) {        int max=0;        String res="";        for(int i=0;i<input.length();i++){            int j=0;            int tmp=1;            while(++j>0){                if((i-j)>=0 && (i+j)<input.length() && input.charAt(i-j)==input.charAt(i+j))                    tmp += 2;                else                    break;            }            if(tmp>max){                max = tmp;                res = input.substring(i-j+1,i+j);            }            if(i+1<input.length()&&input.charAt(i)==input.charAt(i+1)){                j=0;                tmp=2;                while(++j>0){                    if((i-j)>=0 && (i+1+j)<input.length() && input.charAt(i-j)==input.charAt(i+j+1))                        tmp += 2;                    else                        break;                }                if(tmp>max){                    max = tmp;                    res = input.substring(i-j+1,i+j+1);                }            }        }        return res;    }}

Update 2015/09/01: 下面是九章的解法,和上面的差不多

public class Solution {    /**     * @param s input string     * @return the longest palindromic substring     */    public String longestPalindrome(String s) {        // Write your code here        if (s == null || s.length() == 0) {            return "";        }                int length = s.length();            int max = 0;        String result = "";        for(int i = 1; i <= 2 * length - 1; i++){            int count = 1;            while(i - count >= 0 && i + count <= 2 * length  && get(s, i - count) == get(s, i + count)){                count++;            }            count--; // there will be one extra count for the outbound #            if(count > max) {                result = s.substring((i - count) / 2, (i + count) / 2);                max = count;            }        }                return result;    }    private char get(String s, int i) {        if(i % 2 == 0)            return '#';        else             return s.charAt(i / 2);    }}


0 0
原创粉丝点击