[leetcode][5] Longest Palindromic Substring
Posted ekoeko
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode][5] Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
5. 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.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
解析
题目很好理解给定字符串找出最长回文子字符串,首先要清楚怎么样判断是否是回文字符串,然后考虑如何提高效率。
参考答案
自己的(效率低):
class Solution {
public String longestPalindrome(String s) {
String res = "";
int preStart = 0;
int preEnd = 0;
for (int i= 0; i< s.length(); i++) {
for (int j= i; j < s.length(); j++) {
if (j-i+1 > res.length() && isPalindrome(s, i, j, preStart, preEnd)) {
preStart = i;
preEnd = j - 1;
res = s.substring(i, j+1);
}
}
}
return res;
}
public boolean isPalindrome(String s, int start, int end, int preStart, int preEnd) {
while (start < end) {
if (start == preStart && end == preEnd) {
return true;
}
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}
虽然知道要复用上次的回文数的结果,但是不知道怎么利用,很僵硬。。。虽然通过了,用了163ms。
别人的:
public class Solution {
private int lo, maxLen;
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2)
return s;
for (int i = 0; i < len-1; i++) {
extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible
extendPalindrome(s, i, i+1); //assume even length.
}
return s.substring(lo, lo + maxLen);
}
private void extendPalindrome(String s, int j, int k) {
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
if (maxLen < k - j - 1) {
lo = j + 1;
maxLen = k - j - 1;
}
}}
其实可以从中间开始的,向两边遍历,这样判断回文的效率高很多。用dp应该也可以做,回头再看看。
以上是关于[leetcode][5] Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
leetcode--5. Longest Palindromic Substring
#Leetcode# 5. Longest Palindromic Substring
LeetCode题解 #5 Longest Palindromic Substring
[LeetCode] 5 Longest Palindromic Substring