LeetCode_5_LongestPalindromicSubstring(最长回文子序列)

来源:互联网 发布:iphone获取软件 编辑:程序博客网 时间:2024/05/17 06:22

题目: 求给定字符串的最大回文子序列
例如:字符串“abaooxoo”的最大回文子序列为”ooxxoo”;
本章学习了其他博客的相关代码,以及网上的相关资料。
LeetCode原题地址
代码中循环部分的图解:
这里写图片描述


Java代码

/**  * @author ChrisWang * @Date 2016年2月23日 下午10:10:01  * @Description  */public class LongestPalindromicSubstring {    public static void main(String[] args) {        Solution so = new Solution();        String s = "aabbxoxoxodslk";        System.out.println(so.longestPalindrome(s));    }}class Solution {    public String longestPalindrome(String s) {        if(s==null || s.length()==0) {            return "";        }        boolean[][] flag = new boolean[s.length()][s.length()];        String res = "";        int maxLen = 0;        /**         * 以字符串"abaooxoo"为例:         */        for(int i=s.length()-1; i>=0; i--) {            for(int j=i; j<s.length(); j++) {                /*                 * j-i<=2:是指j和i所指向的字符之间虽多有一个字符间隔:"a", "aa", "aba"三种情况                 * flag中的i+1是i后面的一个元素,j-1是j前面的一个元素                 */                if(s.charAt(i)==s.charAt(j) && (j-i<=2 || flag[i+1][j-1])) {                    flag[i][j] = true;                    if(maxLen<j-i+1) { // 记录最长的子序列                        maxLen = j-i+1;                        res = s.substring(i, j+1);                    }                }            }        }        return res;    }}
0 0
原创粉丝点击