From b946853ee8479241f349c721ac15c6922fc4879d Mon Sep 17 00:00:00 2001 From: cchroot <843328872@qq.com> Date: Wed, 11 Nov 2020 21:30:17 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=905.=20=E6=9C=80=E9=95=BF=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=90=E4=B8=B2=E3=80=91=E3=80=90Java=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 提供 Java 代码 --- ...36\346\226\207\345\255\220\344\270\262.md" | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.md" index 9f0f37f..d69b65e 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.md" @@ -131,4 +131,40 @@ string longestPalindrome(string s) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +[cchromt](https://github.com/cchroot) 提供 Java 代码: + +```java +// 中心扩展算法 +class Solution { + public String longestPalindrome(String s) { + // 如果字符串长度小于2,则直接返回其本身 + if (s.length() < 2) { + return s; + } + String res = ""; + for (int i = 0; i < s.length() - 1; i++) { + // 以 s.charAt(i) 为中心的最长回文子串 + String s1 = palindrome(s, i, i); + // 以 s.charAt(i) 和 s.charAt(i+1) 为中心的最长回文子串 + String s2 = palindrome(s, i, i + 1); + res = res.length() > s1.length() ? res : s1; + res = res.length() > s2.length() ? res : s2; + } + return res; + } + + public String palindrome(String s, int left, int right) { + // 索引未越界的情况下,s.charAt(left) == s.charAt(right) 则继续向两边拓展 + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { + left--; + right++; + } + // 这里要注意,跳出 while 循环时,恰好满足 s.charAt(i) != s.charAt(j),因此截取的的字符串为[left+1, right-1] + return s.substring(left + 1, right); + } +} +``` + +做完这题,大家可以去看看 [647. 回文子串](https://leetcode-cn.com/problems/palindromic-substrings/) ,也是类似的题目 -- GitLab