最长回文子串

This commit is contained in:
LingZhaoHui 2020-11-15 23:12:52 +08:00
parent 528f46b646
commit c14d9f3154
1 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,61 @@
package com.leetcode.string;
/**
*
最长回文子串:
给定一个字符串 s找到 s 中最长的回文子串你可以假设 s 的最大长度为 1000
示例 1
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案
示例 2
输入: "cbbd"
输出: "bb"
来源力扣LeetCode
链接https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
* @author zeek
*
*/
public class LongestPalindrome {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) {
return "";
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
public int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
--left;
++right;
}
return right - left - 1;
}
public static void main(String[] args) {
LongestPalindrome rome = new LongestPalindrome();
String s = "cbbd";
String res = rome.longestPalindrome(s);
System.out.println(res);
}
}