最长回文子串 java
时间: 2024-01-02 15:23:02 浏览: 87
以下是使用Java编写的求解最长回文子串的示例代码:
```java
public class LongestPalindromeSubstring {
public static String longestPalindrome(String s) {
if (s == null || s.length() < 2) {
return s;
}
int start = 0;
int maxLength = 1;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > maxLength) {
maxLength = len;
start = i - (len - 1) / 2;
}
}
return s.substring(start, start + maxLength);
}
private static 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;
}
public static void main(String[] args) {
String s = "babad";
System.out.println("Longest palindrome substring: " + longestPalindrome(s)); // 输出:bab
}
}
```
阅读全文