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

题目是求一个字符串的最长回文子串,可以用两种方法,一种是动态规划,用一个矩阵,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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值