原题
给一个字符串,要求返回最长的对称型的子串(又叫最长回文串)
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
答案
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
int strLen = s.length();
int left = 0;
int right = 0;
int len = 1;
int maxStart = 0;
int maxLen = 0;
for (int i = 0; i < strLen; i++) {
left = i - 1;
right = i + 1;
while (left >= 0 && s.charAt(left) == s.charAt(i)) {
len++;
left--;
}
while (right < strLen && s.charAt(right) == s.charAt(i)) {
len++;
right++;
}
while (left >= 0 && right < strLen && s.charAt(right) == s.charAt(left)) {
len = len + 2;
left--;
right++;
}
if (len > maxLen) {
maxLen = len;
maxStart = left;
}
len = 1;
}
return s.substring(maxStart + 1, maxStart + maxLen + 1);
}
}
解析
- 从左到右遍历整个字符串
- 每次遍历都关注一左一右两个字符,如果左边的字符和当前遍历字符相等,则代表出现新的有效值了,使用len来记录下目标串的长度。
- 如果右边的字符和当前字符相等了,同理也更新len。
- 取完相等的值后,就要向左右两侧同时向外取值,left和right同时向外扩展,如果向外的值相等,则目标串长度就要变了,更新len;然后再继续向外直到不相等
- 每一次遍历的最后就会得到一个当前遍历值所对应的目标串,将这个串的长度与其他串比较取最大就得到结果值
说人话
- 从字符串中取出一个左右对称的子串,最简单且效率较高的做法,就是整个字符串中的每个字符,都依次去看看他们有没有对称串
- 看的方法自然是从中间向两侧看,仔细考虑其实也就两种情况,最直白的中心对称式的串,
- 如abcba,以c为中心对称,另一种则为abccba,以中间两个字符对称。
- 所以代码中一开始要判断中心位置是否右相等值,去掉相等值后,其实剩下的就都是中心对称型了,abccba变成了ab(cc)ba,cc合并到了一起,之后就和中心对称型处理一致了,一直同时向两侧扩展
- 经过一系列处理就拿到了这个字符对应的对称串了,接着自然就是用取最大值的方法去取值了,这里只要记录maxLen和maxLeft两个值就可以定位到子串了
个人理解,欢迎指导