import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode maxPalindrome (ListNode head) { // write code here StringBuffer stringBuffer = new StringBuffer(); while (head != null) { stringBuffer.append(head.val); head = head.next; } if(isParame(stringBuffer.toString())){ return null; } ListNode result = null; int length = 0; for(int i=0;i<stringBuffer.length();i++){ for(int j=i+1;j<=stringBuffer.length();j++){ String string = stringBuffer.substring(i,j); if(string.length()>length && isParame(string)){ length = string.length(); ListNode node = new ListNode(0); result = node; for(int k=0;k<string.length();k++){ node.next = new ListNode(string.charAt(k)-'0'); node = node.next; } } } } return result.next; } public static boolean isParame(String s) { StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append(s); return stringBuffer.reverse().toString().equals(s); } }
本题考察的知识点是链表,所用编程语言是java。
先将整条链表的各个结点值添加到集合中,转换成一个字符串然后判断这个字符串是不是回文串,如果不是,则求最大的连续回文串,然后重构整个链表。