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

本文介绍了三种回文相关的算法:寻找字符串中最长的回文子串,判断字符串是否为回文串,以及如何判断一个单链表是否为回文结构。文章提供了详细的代码实现,并对空间复杂度进行了优化,达到O(1)的空间复杂度解决回文链表问题。
摘要由CSDN通过智能技术生成

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.length() && s.charAt(l) == s(r)) {
		l--;
		r++;
	}
	return s.substring(l + 1, r);
}

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.length() - 1;
	while (lo < hi) {
		if (s.charAt(lo) != s.charAt(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;
    }
}

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心海非海_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值