Merge pull request #898 from bourne-3/master

最长回文字串Java实现
This commit is contained in:
程序员Carl
2021-11-16 12:41:01 +08:00
committed by GitHub

View File

@ -262,6 +262,32 @@ public:
## Java
```java
// 双指针 中心扩散法
class Solution {
public String longestPalindrome(String s) {
String s1 = "";
String s2 = "";
String res = "";
for (int i = 0; i < s.length(); i++) {
// 分两种情况:即一个元素作为中心点,两个元素作为中心点
s1 = extend(s, i, i); // 情况1
res = s1.length() > res.length() ? s1 : res;
s2 = extend(s, i, i + 1); // 情况2
res = s2.length() > res.length() ? s2 : res;
}
return res; // 返回最长的
}
public String extend(String s, int start, int end){
String tmp = "";
while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
tmp = s.substring(start, end + 1); // Java中substring是左闭右开的所以要+1
// 向两边扩散
start--;
end++;
}
return tmp;
}
}
```
## Python
@ -316,6 +342,7 @@ class Solution:
## Go
```go
```
## JavaScript