0%

leetcode 5 Solution

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.demo.s5;

/**
* 最长回文子串
*/
public class Solution {
public String longestPalindrome(String s) {
//定义回文子串的起始
int start = 0;
int end = 0;
//遍历字符串字符
for(int i = 0; i< s.length(); i++) {
//以当前字符为中心点扩展
int len1 = expandAroundCenter(s, i, i);
//以当前字符和下一个字符为中心点扩展
int len2 = expandAroundCenter(s, i, i + 1);
//取两种方式扩展最大长度
int max = Math.max(len1, len2);
if(max > end -start + 1) {
//-1防止 当前字符和下一个字符为中心点扩展 导致的问题
start = i - (max-1) / 2;
end = i + max /2;
}
}
return s.substring(start, end + 1);
}

public int expandAroundCenter(String s, int left, int right) {
//左右相等则扩展
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left --;
right ++;
}
//返回扩展的子串长度
return right - left -1;
}
}