To judge whether the linked list is a palindrome and the discussion about the Palindrome series problem

Source: Internet
Author: User

Recently looking at the programmer interview Gold code, in the list part to see a question how to determine whether the linked list is a palindrome string, and then think of White book also has the longest palindrome string of discussion, so want to do a little summary.


first, to determine whether the linked list is a palindrome string

The data structure of a linked list is such a droplet:

public class Node {public
    int val;
    Public Node next;

    Public Node (int val) {
        this.val = val;
        next = null;
    }

    public void Appendtotail (node node) {
        node curnode = this;
        while (Curnode.next!= null) {
            curnode = curnode.next;
        }
        curnode.next = node;
    }
}

This is a question in the interview gold code, the general idea has the following two kinds

1, the first half of the list into the stack, and then start from the second half of the stack with the top element comparison.

The Java code is as follows:

/** * Put the first half of the list into the stack (note odd and even number) * When traversing the second half of the list, a pop-up stack of * elements, check the corresponding position of the elements are the same. * @param head * @return/private static Boolean Ispalindrome (node head) {//If the list is empty or has only one node, then the list is a palindrome string if (head = = NULL | |
    Head.next = = null) {return true;
    //Set speed pointer, control the number of nodes in the stack is half the number of nodes.
    Node Fastnode = head, Slownode = head;
    stack<node> stack = new stack<> ();
        while (Fastnode!= null && fastnode.next!= null) {Stack.push (Slownode);
    Fastnode = fastnode.next.next;//Quick Pointer Walk two steps slownode = slownode.next;//slow pointer walk one step}//If the last quick pointer is empty, the number of linked list nodes is even, and at this time the slow pointer
    Point to the right of the middle position (even if there are two central locations), so there is no need to move back.
    If not NULL, the number of linked list nodes is odd, while the pointer points to a central location,//To compare the need to move one bit backward.
    if (Fastnode!= null) {slownode = Slownode.next; ///traverse the second half of the list and compare it with the elements in the stack while (Slownode!= null &&!stack.isempty ()) {if (Slownode.val!= stack.pe
        Ek (). val) {return false;
        } Slownode = Slownode.next;
    Stack.pop (); } return TRUe }


2, recursion, the first half of the recursive list, returns the result of the corresponding position element with the central position as the axis.

Java code:

/** * Using recursive thinking, the first half of the recursive list, the return of the time * and the second half of the corresponding node comparison, if all corresponding equal * is a palindrome string, otherwise not. * @param head * @return/public boolean ispalindrom (Node head) {//Get the length of the list, the recursive process needs to use int len = Getlindedlength
    (head);
Return Ispalin (head, Len). Ispalindrom; /** * Recursive solver function.
 Each time down recursion, the incoming length minus 2, * to reach the middle end of the list of recursive merge start to judge, return the judgment result.
 * Reached the middle, that is, the recursive end condition has three kinds of conditions: * length is 0: The list is empty * length is 1: indicating that the chain table length is odd, point to the middle node * length is 2: the link table length is even, the middle node has two * at this point to the left of the middle node. * @param head * @param length * @return/Private returnstruct Ispalin (Node head, int length) {if (length = 0) {
        The list is empty returnstruct struct = new returnstruct ();
        Struct.ispalindrom = true;
        Struct.aimnode = null;
    return struct;
        else if (length = = 1) {//List length is odd returnstruct struct = new returnstruct ();
        The intermediate node does not have to judge, returns its next node, which is used for///recursive return after comparing with its previous node Struct.ispalindrom = true;
        Struct.aimnode = Head.next;
    return struct; else if (length = = 2) {//length is even//need to compare the two intermediate nodes are the same, and return//The next node of the middle node on the right, used to recursively return//back to the last node of the middle node on the left, compare returnstruct struct = new returnstruct (); Struct.ispalindrom = Head.val = = Head.next.val?
        True:false;
        Struct.aimnode = Head.next.next;
    return struct;
    //Get the returned comparison results returnstruct returnstruct = Ispalin (Head.next, length-2);
    if (!returnstruct.ispalindrom) {//If the front has a node that does not match palindrome directly returns false return returnstruct; //Compare the current node and the returned node (that is, the symmetric node with the center point of the current node) is the same returnstruct.ispalindrom = Head.val = = ReturnStruct.aimNode.val?
    True:false;
    Returnstruct.aimnode = ReturnStruct.aimNode.next;
return returnstruct;
        /** * Gets the length of the specified list * @param head * @return/private int getlindedlength (Node head) {if (head = = null) {
    return 0;
    Node node = head;
    int len = 0;
        while (node!= null) {len++;
    node = Node.next;
return Len;
 /** * The class used to wrap recursive return values.
 * Because recursion needs to return two values, the class * is used for encapsulation. */class Returnstruct {//Indicates whether the last comparison was a palindrome string Boolean Ispalindrom; Node aimnode;//represents the nodes that are compared to the current node}

second, to find the longest palindrome substring

This problem is a problem in the White book. The main idea is: Enter a string and ask for its longest palindrome substring. When judged, ignores all punctuation and spaces, ignoring case. But the output is intact.

Sample input: Confuciuss say:madam,i ' m Adam.

Sample output: Madam,i ' m Adam

The idea of this problem is also very simple

1. Handle strings, filter punctuation and spaces, and record the position of letters in the original string.

2, to determine whether the filtered string is a palindrome. The string is traversed, and the current position is centered outward, and each diffusion length is combined to check whether the substring is a palindrome. Note the parity of the substring length.

Java code:

/** * Gets the longest back literal string function. * Iterate through each element, starting with the current element, and then looking at itself as the Center (parity) of the * length of the substring is a palindrome string, and update the current oldest string length and position * @param string * @return/public string Getlps (
    String string) {if (string = = null) {return null;
    } if (string.length () = = 0) {return "";
    } char[] STRs = String.tochararray ();
    Filter useless characters, used to store the characters to find char[] m = new Char[strs.length];
    The position of the character used to record the corresponding position in the original array int[] p = new Int[strs.length];
    int mlen = 0;
            for (int i = 0; i < strs.length i++) {if (Character.isalphabetic (Strs[i])) {P[mlen] = i;
        m[mlen++] = Character.tolowercase (Strs[i]);
    an int maxlen = Integer.min_value;
    int x = 0, y = 0; Iterates through the array, checking the substring of different lengths for the palindrome string for (int i = 0; i < Mlen; i++) {/or odd-length substring for (int j = 0; i-j) in the center of the current character. = 0 && i + j < Mlen;
            J + +) {if (M[i-j]!= m[i + j]) {break;
              } if (2 * j + 1 > MaxLen) {  MaxLen = 2 * j + 1;
            x = p[i-j];//records the most firstborn string position y = p[i + j]; }///Even length substring for (int j = 0; i-j >= 0 && i + j + 1 < Mlen; J +) {if (M[i-j]!= m[i + j + 1])
            {break;
                } if (2 * j + 2 > MaxLen) {maxlen = 2 * j + 2;
                x = P[i-j];
            y = p[i + j + 1];
    }} StringBuilder Build = new StringBuilder ();
    for (int i = x; i <= y; i++) {build.append (strs[i));
return build.tostring (); }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.