鱼C论坛

 找回密码
 立即注册
查看: 2225|回复: 0

[学习笔记] leetcode 5. Longest Palindromic Substring

[复制链接]
发表于 2019-8-29 12:50:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Seawolf 于 2019-8-31 09:54 编辑
  1. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

  2. Example 1:

  3. Input: "babad"
  4. Output: "bab"
  5. Note: "aba" is also a valid answer.
  6. Example 2:

  7. Input: "cbbd"
  8. Output: "bb"
复制代码


Dp

  1. class Solution {
  2.    
  3.     public String longestPalindrome(String s) {
  4.         
  5.         if(s.length() == 0) return s;
  6.         
  7.         int len = s.length();
  8.         
  9.         int max = 0;
  10.         
  11.         String res = "";
  12.         
  13.         boolean dp[][] = new boolean[len][len];
  14.         
  15.         for(int j = 0; j< len; j++){
  16.             
  17.             for(int i = 0 ; i <= j; i++){
  18.                
  19.                 dp[i][j] = s.charAt(i)== s.charAt(j) && (j - i <= 2 || dp[i+1][j-1]);
  20.                     
  21.                
  22.                 if(dp[i][j]){
  23.                     
  24.                     
  25.                     if(j - i + 1 > max){
  26.                     
  27.                         max = j - i + 1;
  28.                     
  29.                         res = s.substring(i,j+1);
  30.                 }
  31.                     
  32.                 }
  33.                
  34.                
  35.             }
  36.             
  37.             
  38.         }
  39.         
  40.         return res;

  41. }

  42. }
复制代码


  1. class Solution {
  2.    
  3.     String res = "";
  4.    
  5.     public String longestPalindrome(String s) {
  6.         
  7.         if(s == null || s.length() == 0) return s;
  8.         
  9.         int len = s.length();
  10.         
  11.         for(int i = 0; i< len; i++){
  12.             
  13.             help(s,i,i);
  14.             help(s,i,i+1);
  15.         }
  16.         
  17.         return res;

  18. }
  19.    
  20.     public void help(String s, int left, int right){
  21.         
  22.         while(left >= 0 && right< s.length() && s.charAt(left) == s.charAt(right)){
  23.             
  24.             left --;
  25.             right++;
  26.         }
  27.         
  28.         String cur = s.substring(left+1, right);
  29.         
  30.         if(cur.length() > res.length()){
  31.             
  32.             res = cur;
  33.         }
  34.     }
  35.    
  36. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 19:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表