Problem: 5. 最长回文子串
题目描述
思路
1.我们利用双指针从中间向两边扩散来判断是否为回文串,则关键是找到以s[i]为中心的回文串;
2.我们编写一个函数string palindrome(string &s, int left, int right)用于返回以索引为i作为中心向两边的的回文子串
3.由于可能出现奇数或者偶数长度的回文串,所以我们需要在遍历时,求出**palindrome(s, i, i)与palindrome(s, i, i + 1)**的回文串,并取出其中的较大值
复杂度
时间复杂度:
O ( N 2 ) O(N^2) O(N2);其中 N N N为字符串的长度
空间复杂度:
O ( N ) O(N) O(N)
Code
class Solution {
/**
* Longest Palindromic Substring
*
* @param s Given string
* @return String
*/
public String longestPalindrome(String s) {
String res = "";
for (int i = 0; i < s.length(); ++i) {
// The longest callback substring centered on s[i]
String s1 = palindrome(s, i, i);
// Longest callback substring centered on s[i] and s[i+1]
String s2 = palindrome(s, i, i + 1);
// res = longest(res, s1, s2)
res = res.length() > s1.length() ? res : s1;
res = res.length() > s2.length() ? res : s2;
}
return res;
}
/**
* Gets the longest palindrome string between [left,right]
*
* @param s Given string
* @param left Left pointer
* @param right Right pointer
* @return string
*/
private String palindrome(String s, int left, int right) {
// Prevent index overreach
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
// Double Pointers, spread out to both sides
left--;
right++;
}
// Returns the longest palindrome string centered on s[l] and s[r]
return s.substring(left + 1, right);
}
}