标签:hat art longest not you ret i+1 oss bool
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
标签:hat art longest not you ret i+1 oss bool
原文地址:https://www.cnblogs.com/ekoeko/p/9611125.html