未验证 提交 790d1c6a 编写于 作者: B BruceCat 提交者: GitHub

【5. 最长回文子串】【Java】

【5. 最长回文子串】【Java】
......@@ -131,4 +131,40 @@ string longestPalindrome(string s) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ 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/) ,也是类似的题目
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册