Skip to content

Commit 766e972

Browse files
committed
最长回文字串Java实现
1 parent da87ff9 commit 766e972

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

problems/0005.最长回文子串.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,32 @@ public:
265265
## Java
266266

267267
```java
268+
// 双指针 中心扩散法
269+
class Solution {
270+
public String longestPalindrome(String s) {
271+
String s1 = "";
272+
String s2 = "";
273+
String res = "";
274+
for (int i = 0; i < s.length(); i++) {
275+
// 分两种情况:即一个元素作为中心点,两个元素作为中心点
276+
s1 = extend(s, i, i); // 情况1
277+
res = s1.length() > res.length() ? s1 : res;
278+
s2 = extend(s, i, i + 1); // 情况2
279+
res = s2.length() > res.length() ? s2 : res;
280+
}
281+
return res; // 返回最长的
282+
}
283+
public String extend(String s, int start, int end){
284+
String tmp = "";
285+
while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
286+
tmp = s.substring(start, end + 1); // Java中substring是左闭右开的,所以要+1
287+
// 向两边扩散
288+
start--;
289+
end++;
290+
}
291+
return tmp;
292+
}
293+
}
268294
```
269295

270296
## Python
@@ -292,11 +318,13 @@ class Solution:
292318
## Go
293319

294320
```go
321+
295322
```
296323

297324
## JavaScript
298325

299326
```js
327+
300328
```
301329

302330
-----------------------

0 commit comments

Comments
 (0)