9-line recursive Java solution


  • 0
    A
    public class Solution {
        ListNode first;
        public boolean isPalindrome(ListNode head) {
            first = head;
            return helper(head);
        }
        public boolean helper(ListNode last) {
            if (last==null) return true;
            boolean pre = helper(last.next);
            boolean cur = first.val == last.val;
            first = first.next;
            return cur && pre;
        }
    }
    

  • 0
    W

    so coooooooooool

    I had been looking and thing for the recursive solution so long times. Eventurally, I got it today.

    It give me two reminders: 1. keep the first as a globe variable, and write " first = first.next" statement in the recursive method.

    1. need keep the previous result as well, but not just the current result. otherwise it will lost previous value. so "return cur && pre". In other words, it will return false as long as one of the result is false

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.