题解 | #牛群编号的回文顺序II#
牛群编号的回文顺序II
https://www.nowcoder.com/practice/e887280579bb4d91934378ea359f632e
题目考察的知识点
考察链表的相关操作
题目解答方法的文字分析
需要借助集合,将节点值添加到集合中去并转换为字符串,通过判断是否为回文串从而求出最大的回文链表。返回的时候根据最大回文串重新构建起链表即可。
本题解析所用的编程语言
使用Java语言解答
完整且正确的编程代码
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); } }