[LeetCode] 234. Palindrome Linked List 回文鏈表


 

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

 

這道題讓我們判斷一個鏈表是否為回文鏈表,LeetCode 中關於回文串的題共有六道,除了這道,其他的五道為 Palindrome NumberValidate PalindromePalindrome PartitioningPalindrome Partitioning II 和 Longest Palindromic Substring。鏈表比字符串難的地方就在於不能通過坐標來直接訪問,而只能從頭開始遍歷到某個位置。那么根據回文串的特點,我們需要比較對應位置的值是否相等,一個非常直接的思路就是先按順序把所有的結點值都存入到一個棧 stack 里,然后利用棧的后入先出的特性,就可以按順序從末尾取出結點值了,此時再從頭遍歷一遍鏈表,就可以比較回文的對應位置了,若不同直接返回 false 即可,參見代碼如下:

 

解法一:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *cur = head;
        stack<int> st;
        while (cur) {
            st.push(cur->val);
            cur = cur->next;
        }
        while (head) {
            int t = st.top(); st.pop();
            if (head->val != t) return false;
            head = head->next;
        }
        return true;
    }
};

 

我們也可以用迭代的形式來實現,此時需要使用一個全局變量結點 cur,先初始化為頭結點,可以有兩種寫法,一種寫在函數外面的全局變量,或者是在遞歸函數的參數中加上引用,也表示使用的是全局變量。然后對頭結點調用遞歸函數,在遞歸函數中,首先判空,若為空則直接返回 true,否則就對下一個結點調用遞歸函數,若遞歸函數返回 true 且同時再當前結點值跟 cur 的結點值相同的話,就表明是回文串,否則就不是,注意每次 cur 需要指向下一個結點,參見代碼如下:

 

解法二:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *cur = head;
        return helper(head, cur);
    }
    bool helper(ListNode* node, ListNode*& cur) {
        if (!node) return true;
        bool res = helper(node->next, cur) && (cur->val == node->val);
        cur = cur->next;
        return res;
    }
};

 

其實上面的兩種解法重復比較一些結點,因為只要前半個鏈表和后半個鏈表對應值相等,就是一個回文鏈表,而並不需要再比較一遍后半個鏈表,所以我們可以找到鏈表的中點,這個可以用快慢指針來實現,使用方法可以參見之前的兩篇 Convert Sorted List to Binary Search Tree 和 Reorder List,使用快慢指針找中點的原理是 fast 和 slow 兩個指針,每次快指針走兩步,慢指針走一步,等快指針走完時,慢指針的位置就是中點。我們還需要用棧,每次慢指針走一步,都把值存入棧中,等到達中點時,鏈表的前半段都存入棧中了,由於棧的后進先出的性質,就可以和后半段鏈表按照回文對應的順序比較了,參見代碼如下:

 

解法三:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (!head || !head->next) return true;
        ListNode *slow = head, *fast = head;
        stack<int> st{{head->val}};
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
            st.push(slow->val);
        }
        if (!fast->next) st.pop();
        while (slow->next) {
            slow = slow->next;
            int tmp = st.top(); st.pop();
            if (tmp != slow->val) return false;
        }
        return true;
    }
};

 

這道題的 Follow up 讓我們用 O(1) 的空間,那就是說我們不能使用 stack 了,那么如何代替 stack 的作用呢,用 stack 的目的是為了利用其后進先出的特點,好倒着取出前半段的元素。那么現在不用 stack 了,如何倒着取元素呢。我們可以在找到中點后,將后半段的鏈表翻轉一下,這樣我們就可以按照回文的順序比較了,參見代碼如下:

 

解法四:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (!head || !head->next) return true;
        ListNode *slow = head, *fast = head;
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *last = slow->next, *pre = head;
        while (last->next) {
            ListNode *tmp = last->next;
            last->next = tmp->next;
            tmp->next = slow->next;
            slow->next = tmp;
        }
        while (slow->next) {
            slow = slow->next;
            if (pre->val != slow->val) return false;
            pre = pre->next;
        }
        return true;
    }
};

 

Githbu 同步地址:

https://github.com/grandyang/leetcode/issues/234

 

類似題目:

Palindrome Number

Validate Palindrome

Palindrome Partitioning

Palindrome Partitioning II

Longest Palindromic Substring

Reverse Linked List

 

參考資料:

https://leetcode.com/problems/palindrome-linked-list/

https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand

https://leetcode.com/problems/palindrome-linked-list/discuss/148220/Javathe-clear-method-with-stack

https://leetcode.com/problems/palindrome-linked-list/discuss/64490/My-easy-understand-C%2B%2B-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM