题解 | #牛群编号的回文顺序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);
}
}

