华为机试HJ85题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
Java实现
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { // 判断一个字符串是否为回文字符串 // 直接看翻转后的字符串是否和原字符串相等即可 public static boolean IsHuiWenString(String strSrc) { StringBuilder sb = new StringBuilder(strSrc); String destStr = sb.reverse().toString(); return strSrc.equals(destStr); } // 获取字符串strSrc的所有子串中,为回文串的最大长度 public static int GetLongestCount(String strSrc) { int maxCount = 0; for (int i = 0; i < strSrc.length(); i++) { for (int j = i + 1; j < strSrc.length(); j++) { String subStr = strSrc.substring(i, j + 1); if (IsHuiWenString(subStr)) { maxCount = Math.max(maxCount, subStr.length()); } } } return maxCount; } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String strSrc = in.nextLine().toString(); System.out.println(GetLongestCount(strSrc)); } } }