leetcode: 5. Longest Palindromic Substring (java)
2016-06-20 21:09
531 查看
题目链接:https://leetcode.com/problems/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.
解析:
两种动态规划:(1)dp[i][j],按照i-j的差值来构造。即外循环为差值diff,从1到length-1。里面便是左边缘的循环,即dp[i][i+diff]
(2)外循环为子串的左边缘位置,内循环为右边缘位置;
上面的递推关系都是一样的,dp[i][j] = dp[i+1][j-1] (s[i] == s[j])
第一种我用的c 语言实现的,下面为第二种的java实现代码:
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return "";
boolean[][] isPali = new boolean[s.length()][s.length()];
String res = "";
int maxLen = 0;
for (int i = s.length()-1; i >= 0; i--){
for (int j = i; j < s.length(); j++){
if (s.charAt(i) == s.charAt(j) && (j-i <= 2 || isPali[i+1][j-1])){
isPali[i][j] = true;
if (maxLen < j-i+1){
maxLen = j-i+1;
res = s.substring(i, j+1);
}
}
}
}
return res;
}
}
题目:
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[i][j],按照i-j的差值来构造。即外循环为差值diff,从1到length-1。里面便是左边缘的循环,即dp[i][i+diff]
(2)外循环为子串的左边缘位置,内循环为右边缘位置;
上面的递推关系都是一样的,dp[i][j] = dp[i+1][j-1] (s[i] == s[j])
第一种我用的c 语言实现的,下面为第二种的java实现代码:
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return "";
boolean[][] isPali = new boolean[s.length()][s.length()];
String res = "";
int maxLen = 0;
for (int i = s.length()-1; i >= 0; i--){
for (int j = i; j < s.length(); j++){
if (s.charAt(i) == s.charAt(j) && (j-i <= 2 || isPali[i+1][j-1])){
isPali[i][j] = true;
if (maxLen < j-i+1){
maxLen = j-i+1;
res = s.substring(i, j+1);
}
}
}
}
return res;
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解