5:最长回文子串

This commit is contained in:
huangge1199@hotmail.com 2021-04-30 00:15:43 +08:00
parent a1bdf655f1
commit f4b049d5c8
3 changed files with 147 additions and 1 deletions

View File

@ -0,0 +1,104 @@
//给你一个字符串 s找到 s 中最长的回文子串
//
//
//
// 示例 1
//
//
//输入s = "babad"
//输出"bab"
//解释"aba" 同样是符合题意的答案
//
//
// 示例 2
//
//
//输入s = "cbbd"
//输出"bb"
//
//
// 示例 3
//
//
//输入s = "a"
//输出"a"
//
//
// 示例 4
//
//
//输入s = "ac"
//输出"a"
//
//
//
//
// 提示
//
//
// 1 <= s.length <= 1000
// s 仅由数字和英文字母大写和/或小写组成
//
// Related Topics 字符串 动态规划
// 👍 3593 👎 0
package leetcode.editor.cn;
import java.util.Collections;
//5:最长回文子串
public class LongestPalindromicSubstring {
public static void main(String[] args) {
//测试代码
Solution solution = new LongestPalindromicSubstring().new Solution();
//bab
System.out.println(solution.longestPalindrome("babad"));
//bb
System.out.println(solution.longestPalindrome("cbbd"));
//a
System.out.println(solution.longestPalindrome("a"));
//a
System.out.println(solution.longestPalindrome("ac"));
//ccc
System.out.println(solution.longestPalindrome("ccc"));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String longestPalindrome(String s) {
int length = s.length();
if (length < 2) {
return s;
}
boolean[][] bl = new boolean[length][length];
for (int i = 0; i < length; i++) {
bl[i][i] = true;
}
int index = 0;
int max = 1;
for (int i = 2; i <= length; i++) {
for (int start = 0; start < length && i + start - 1 < length; start++) {
int end = i + start - 1;
if (s.charAt(start) != s.charAt(end)) {
bl[start][end] = false;
} else {
if (i <= 3) {
bl[start][end] = true;
} else {
bl[start][end] = bl[start + 1][end - 1];
}
}
if (bl[start][end] && i > max) {
max = i;
index = start;
}
}
}
return s.substring(index, index + max);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,42 @@
<p>给你一个字符串 <code>s</code>,找到 <code>s</code> 中最长的回文子串。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>s = "babad"
<strong>输出:</strong>"bab"
<strong>解释:</strong>"aba" 同样是符合题意的答案。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>s = "cbbd"
<strong>输出:</strong>"bb"
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>s = "a"
<strong>输出:</strong>"a"
</pre>
<p><strong>示例 4</strong></p>
<pre>
<strong>输入:</strong>s = "ac"
<strong>输出:</strong>"a"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> 仅由数字和英文字母(大写和/或小写)组成</li>
</ul>
<div><div>Related Topics</div><div><li>字符串</li><li>动态规划</li></div></div>\n<div><li>👍 3593</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long