leedcode做题总结, 题目Longest Palindromic Substring 5
2015-01-25 06:46
447 查看
题目是求一个字符串的最长回文子串,可以用两种方法,一种是动态规划,用一个矩阵,boolean[i,j] 表示字符串从i-j是否为一个回文串,我用的方法是直接判断,DP方法见http://www.cnblogs.com/dollarzhaole/archive/2013/07/22/3207364.html
Update 2015/09/01: 下面是九章的解法,和上面的差不多
class Solution11 { public String longestPalindrome(String input) { int max=0; String res=""; for(int i=0;i<input.length();i++){ int j=0; int tmp=1; while(++j>0){ if((i-j)>=0 && (i+j)<input.length() && input.charAt(i-j)==input.charAt(i+j)) tmp += 2; else break; } if(tmp>max){ max = tmp; res = input.substring(i-j+1,i+j); } if(i+1<input.length()&&input.charAt(i)==input.charAt(i+1)){ j=0; tmp=2; while(++j>0){ if((i-j)>=0 && (i+1+j)<input.length() && input.charAt(i-j)==input.charAt(i+j+1)) tmp += 2; else break; } if(tmp>max){ max = tmp; res = input.substring(i-j+1,i+j+1); } } } return res; } }
Update 2015/09/01: 下面是九章的解法,和上面的差不多
public class Solution { /** * @param s input string * @return the longest palindromic substring */ public String longestPalindrome(String s) { // Write your code here if (s == null || s.length() == 0) { return ""; } int length = s.length(); int max = 0; String result = ""; for(int i = 1; i <= 2 * length - 1; i++){ int count = 1; while(i - count >= 0 && i + count <= 2 * length && get(s, i - count) == get(s, i + count)){ count++; } count--; // there will be one extra count for the outbound # if(count > max) { result = s.substring((i - count) / 2, (i + count) / 2); max = count; } } return result; } private char get(String s, int i) { if(i % 2 == 0) return '#'; else return s.charAt(i / 2); } }
相关文章推荐
- leedcode做题总结, 题目Unique Binary Search TreesI/II95/96
- leedcode做题总结,题目Same Tree 2012/09/03
- leedcode做题总结,题目Reverse Integer----- 2011/12/25
- leedcode做题总结,题目Find Minimum in Rotated Sorted ArrayI/II 153/154
- leedcode做题总结,题目Two Sum2011-03-13
- leedcode做题总结,题目Sum Root to Leaf Numbers 2013/02/18
- leedcode做题总结,题目Remove Element 2012/02/16
- leedcode做题总结,题目Evaluate Reverse Polish Notation 2013/11/27
- leetcode做题总结,题目Longest Substring Without Repeating Characters
- leedcode做题总结,题目Linked List Cycle I/II 13/10/28-30
- leedcode做题总结,题目Binary Tree Zigzag Level Order Traversal 2012/09/28
- leedcode做题总结,题目Pascal's Triangle I/II-------2012/10/28
- leedcode做题总结, 题目Construct Binary Tree from Preorder。。。105/106
- leedcode做题总结,题目Reorder List 13/11/12
- leedcode做题总结,题目Rotate Image 2012/03/17
- leedcode做题总结,题目Balanced Binary Tree 2012/10/08
- [leedcode 5]Longest Palindromic Substring
- leedcode做题总结,题目Median of Two Sorted Arrays----- 2011/03/27
- leedcode做题总结,题目Convert Sorted Array to Binary Search Tree 2013/02/18
- leedcode做题总结,题目Maximum Depth of Binary Tree-------2012/09/29