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 9f0f37f526068ecfda595768105f1e194afb258d..d69b65ef16e6b023bd235e1ff3593b7b777e14f0 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/) ,也是类似的题目