5. Longest Palindromic Substring
2016-07-15 10:36
211 查看
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.
方法1:
DP找出[a,b]是否是回文串,在这个过程中,可以记录最大的回文串,O(N^2)
方法2:
逐个字符扫描,看以当前字符是否能够扩展形成的回文串最长是多长,因为回文串的对称中心有可能是一个字符,有可能是一个位置,
所以尝试扩展的时候要分情况,形成奇串和偶串的处理稍有不同。最坏情况O(N^2)
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.
方法1:
DP找出[a,b]是否是回文串,在这个过程中,可以记录最大的回文串,O(N^2)
public static String longestPalindrome(String s) { int len=s.length(); if(len<1) return ""; boolean[][] dp=new boolean[len][len]; int indexi=0,indexj=0,max=Integer.MIN_VALUE; for(int i=len-1;i>=0;i--) for(int j=0;j<len;j++) { if(i>=j) dp[i][j]=true; else { dp[i][j]=dp[i+1][j-1]&&(s.charAt(i)==s.charAt(j)); if(dp[i][j]) if(Math.abs(i-j)>max) { max=Math.abs(i-j); indexi=i; indexj=j; } } } return s.substring(indexi, indexj+1); }
方法2:
逐个字符扫描,看以当前字符是否能够扩展形成的回文串最长是多长,因为回文串的对称中心有可能是一个字符,有可能是一个位置,
所以尝试扩展的时候要分情况,形成奇串和偶串的处理稍有不同。最坏情况O(N^2)
public static String longestPalindrome(String str) { if (str.isEmpty()) return null; int[] odd, even; int max = 0, a = 0, b = 0; for (int i = 0; i < str.length(); i++) { odd = expandPalindrome(str, i - 1, i + 1); if (odd[1] - odd[0] > max) { a = odd[0]; b = odd[1]; max = b - a; } even = expandPalindrome(str, i, i + 1); if (even[1] - even[0] > max) { a = even[0]; b = even[1]; max = b - a; } } return str.substring(a, b); } private static int[] expandPalindrome(String str, int a, int b) { while (a >= 0 && b < str.length() && str.charAt(a) == str.charAt(b)) { a--; b++; } return new int[]{a + 1,b}; }
相关文章推荐
- poj 3040 Allowance
- EasyUI常用组件(基础)
- Exception in thread “main” java.lang.IncompatibleClassChangeError: Found interface org.apache.hadoop
- has leaked window com.android.internal.policy.impl.PhoneWindow$ that was originally added here
- EasyUI常用组件(基础)
- EasyUI常用组件(基础)
- iOS UILabel:宽度固定,自动高度显示全部文字
- maven中央仓库
- Cmarkup对xml文件的解析
- 数据库中文乱码解决方案总结,tomcat+mysql+hibernate
- LNMP的并发考虑与资源分配
- HDU1231
- java中|与||,&与&&到底有什么区别呢?
- FL2440开发板 platform_led驱动及应用程序
- 【Java进阶】利用APT优雅的实现统一日志格式
- CentOS6.7上搭建httpd-2.2
- HDU 2669 Romantic
- 中级项目知识点
- 剑指offer-5-面试34:丑数(优化时间和空间效率)
- HTML5 video 和 audio