力扣算法 Java 刷题笔记【链表篇】hot100(四)如何判断回文链表(简单) 3

1. 寻找回文串

地址: https://labuladong.gitee.io/algo/2/17/19/ string palindrome(string s, int l, int r)
2021/11/26

/**
1、length() 方法是针对字符串来说的,要求一个字符串的长度就要用到它的length()方法;
2、length 属性是针对 Java 中的数组来说的,要求数组的长度可以用其 length 属性;
3、Java 中的 size() 方法是针对泛型集合说的, 如果想看这个泛型有多少个元素, 就调用此方法来查看!
*/

string palindrome(string[] s, int l, int r) {
    
    
	while (l >= 0 && r < s.size() && s[l] == s[r]) {
    
    
		l--;
		r++;
	}
	return subString(l + 1, r - l - 1);
}

2. 判断一个字符串是否为回文串

地址: https://labuladong.gitee.io/algo/2/17/19/ bool isPalindrome(string s)
2021/11/26

bool isPalindrome(string[] s) {
    
    
	int lo = 0, hi = s.size() - 1;
	while (lo < hi) {
    
    
		if (s[lo] != s[hi]) {
    
    
			return false;
		}
		lo++;
		hi--;
	}
	return true;
}

3. 判断回文单链表(简单)

地址: https://leetcode-cn.com/problems/palindrome-linked-list/
2021/11/29
做题反思:AC

优化空间复杂度

O(n) 时间复杂度和 O(1) 空间复杂度

class Solution {
    
    
    public boolean isPalindrome(ListNode head) {
    
    
        ListNode fast = head, slow = head;
        while (fast != null && fast.next != null) {
    
    
            slow = slow.next;
            fast = fast.next.next;
        }
        // 此处用 fast 判断, 避免 NPE
        if (fast != null) {
    
    
            slow = slow.next;
        }
        ListNode newNode = reverse(slow);
        while (newNode != null) {
    
    
            // 此处为比较 结点值
            if (newNode.val != head.val) {
    
    
                return false;
            }
            newNode = newNode.next;
            head = head.next;
        }
        return true;
    }

    ListNode reverse(ListNode a) {
    
    
        ListNode pre = null, cur = a, nxt = a;
        while (cur != null) {
    
    
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46644403/article/details/121548633