题解 | #牛群编号的回文顺序II#

牛群编号的回文顺序II

https://www.nowcoder.com/practice/e887280579bb4d91934378ea359f632e?tpId=354&tqId=10595827&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354

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。

解题的思路:

先将整条链表的各个结点值添加到集合中,转换成一个字符串然后判断这个字符串是不是回文串,如果不是,则求最大的连续回文串,然后重构整个链表

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务