zoukankan      html  css  js  c++  java
  • Longest Palindromic Substring

    描述
    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.

    分析
    最长回文子串,非常经典的题。
    思路一:

    暴力枚举,以每个元素为中间元素,同时从左右出发,复杂度 O(n^2)

    思路二:记忆化搜索,复杂度 O(n^2)

    设 f[i][j] 表示 [i,j] 之间的最长回文子串,递推方程如
    下:
    f[i][j] = if (i == j)  S[i]
    if (S[i] == S[j] && f[i+1][j-1] == S[i+1][j-1]) S[i][j]
    else max(f[i+1][j-1], f[i][j-1], f[i+1][j])
    思路三:动规,复杂度 O(n^2)
    设状态为 f(i,j),表示区间 [i,j] 是否为回文串,则状态转移方

    思路三:Manacher’s Algorithm, 复杂度 O(n)。详细解释见 http://leetcode.com/2011/11/longestpalindromic-substring-part-ii.html 。

    代码

     1 public class LongestPalindromicSubstring {
     2 
     3     public static void main(String[] args) {
     4         // TODO Auto-generated method stub
     5         String s="abcdfrg0A man, a plan, a canal: Panama0abcfegh";
     6         System.out.println(longestPalindromicSubstring(s));
     7     }
     8 
     9     
    10     public static boolean validPalindrome(String str) {
    11         if (str=="") 
    12             return true;
    13 //        String regex= "/[^\u4e00-\u9fa5\w]/g";
    14         String regex= "[\p{Punct}\p{Space}]+"; //去标点符号的正则表达式, 但不能去“”和中文标点
    15         str=str.replaceAll(regex,"");
    16         String strlow=str.toLowerCase();
    17 //        return strlow;
    18         char[] ch=strlow.toCharArray();
    19     
    20         for(int i=0;i<ch.length;i++) {
    21             int j=ch.length-1-i;
    22             if(i<=j) {
    23                if(ch[i]==ch[j]) {
    24                    continue;
    25                }else {
    26                    return false;
    27                }
    28             }
    29         }
    30         return true;
    31     }
    32     
    33     public static String longestPalindromicSubstring(String s) {
    34         if(s=="") return null;
    35         int i=0,j=0;
    36         int maxl=0;
    37         String longest="";
    38         for(i=0;i<s.length();i++) {
    39             for(j=i;j<s.length()-1;j++) {
    40                 String temp=s.substring(i, j+1);
    41                 if(validPalindrome(temp)) {
    42                     if(maxl<temp.length()) {
    43                         maxl=temp.length();
    44                         longest=temp;
    45                     }
    46                 }
    47             }
    48         }
    49         return longest;
    50     }
  • 相关阅读:
    vtk体绘制时采样的起点使用噪声纹理来进行扰动
    转:轻松搞死VS
    虚拟华师(UDK)
    虚拟手术中的血流模拟(Physx+OpenGL)
    要找工作了,研究工作得暂停了
    MC+多个emitter成功把撕裂场景基本解决了
    鸭梨很大
    这世界好人多啊
    JS代码的格式化和压缩
    FusionCharts使用实例
  • 原文地址:https://www.cnblogs.com/ncznx/p/9180455.html
Copyright © 2011-2022 走看看