程序如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str = "";
Scanner in = new Scanner(System.in);
int max=0; //存放最大长度
String longestPalindrome=""; //存放最长回文
str = in.nextLine();
int length = str.length();
for (int i = 0; i < length; i++) { //遍历所有子串
for (int j = i + 1; j < length; j++) {
int len = j - i;
String curr = str.substring(i, j + 1);
if (isPalindrome(curr)) {
if (len > max) {
longestPalindrome = curr;
max = len;
}
}
}
}
return longestPalindrome;
}
public static boolean isPalindrome(String s) { //判断是否为回文
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
}
本文介绍了一种使用Java实现的算法,该算法用于找出给定字符串中的最长回文子串。通过双重循环遍历所有可能的子串,并检查每个子串是否为回文来实现。同时提供了一个判断字符串是否为回文的辅助方法。
963

被折叠的 条评论
为什么被折叠?



