码迷,mamicode.com
首页 > 其他好文 > 详细

*5. Longest Palindromic Substring (dp) previous blogs are helpful

时间:2018-06-02 12:55:40      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:ret   longest   bad   stp   ==   string   neu   art   inpu   

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

 

solution: using dp: i : start index, j : ending index

given fixed size(number of subString), check each substring(from s)

class Solution {
    public String longestPalindrome(String s) {
        //nature structure
        //given fixed step(number,size), check each subString
        //dp -- from 0 to n-1
        int max = 0;
        String res = "";
        int n = s.length();
        boolean[][] dp = new boolean[n][n];
        for(int i = 0; i<n;i++){//fixed number
            for(int j = 0; j+i<n; j++){//start inex
                if(s.charAt(j) == s.charAt(j+i)){
                    if(i<2 || dp[j+1][j+i-1]){ // 0 or 1
                        dp[j][j+i] = true;
                        dp[j+i][j] = true;
                        if(max<i+1){
                            max = i+1;
                            res = s.substring(j,j+i+1);
                        }
                    }
                }
            }
        }
        //System.out.println(max);
        return res;
        
    }
}

 more solution here

https://leetcode.com/problems/longest-palindromic-substring/solution/

 

*5. Longest Palindromic Substring (dp) previous blogs are helpful

标签:ret   longest   bad   stp   ==   string   neu   art   inpu   

原文地址:https://www.cnblogs.com/stiles/p/leetcode5.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!