首页 > 其他 > 详细

Longest Palindromic Substring2015年6月20日

时间:2015-06-20 21:57:21      阅读:249      评论:0      收藏:0      [点我收藏+]

 

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 {
StringBuilder longest = new StringBuilder("");

public String longestPalindrome(String s) {
        String ss;
        int len = s.length();
        int max = 0;
        int sublen = 0;
        String result = "";
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                ss = s.substring(i, j);
                int index = s.indexOf(reverse(ss),j-1);
                if (index == j - 1) {
                    sublen = 2 * (j - 1 - i) + 1;
                    if (sublen > max) {
                        max = sublen;
                        result = s.substring(i, max+i);
                    }
                    continue;
                } else if (index == j) {
                    sublen = 2 * (j - i);
                    if (sublen > max) {
                        max = sublen;
                        result = s.substring(i, max+i);
                    }
                    continue;
                } else {
                    continue;
                }
            }
        }

        return result;
    }

    public String reverse(String s) {
        StringBuilder sb = new StringBuilder(s);
        sb.reverse();
        return sb.toString();
    }
}

方法正确性是没有问题的,先挨个取子串,查找反串。但在LeetCode上会报超时错误。

参考讨论区的解答

public class Solution {
StringBuilder longest = new StringBuilder("");

public String longestPalindrome(String s) {
    if (s.length() <= 1) return s;

    for (int i = 0; i < s.length(); i++) {
        expand(s, longest, i, i); //odd
        expand(s, longest, i, i + 1); //even
    }

    return longest.toString();
}

private void expand(String s, StringBuilder longest, int i, int j) {
    while (i >= 0 && j < s.length()) {
        if (s.charAt(i) == s.charAt(j)) {
            if (j - i + 1 > longest.length()) {
                longest.delete(0, longest.length());
                longest.append(s.substring(i, j + 1));
            }
            i--;
            j++;
        }
        else
            break;
    }
}
}

 

Longest Palindromic Substring2015年6月20日

原文:http://www.cnblogs.com/hixin/p/4591058.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!