一、什么是回文结构?
回文结构就是类似于ABBA、ABA、A的形式
示例1:a -> b -> c -> c - >b - >a
示例2:a -> b -> a
示例3:a
示例4:abccba
二、回文结构判断方法
1.字符串类型
将字符串转换成数组之后,反转数组,然后将数组 的内容拼接转换成字符串,与源字符串比对
let str = 'abccba'
function isPalindrome(str){
if(str.length === 1){
return true
}else{
let reverseStr = Array.from(str).reverse().join(' ');
if(reverseStr == str){
return true;
}else{
return false;
}
}
}
2.链表类型
- 使用栈的方式,遍历单链表,将链表中的每个节点添加到数组中,然后再次遍历链表,同时对数组进行弹栈操作,依次比对。因为栈是后进先出,所以是按照链表的最后一个节点开始弹栈
function isPalindrome = function(head) {
if(head === null || head.next === null){
return true
}
// 1.使用栈的方式
let current = head;
let stack = new Array();
// 遍历链表,入栈
while (current != null) {
stack.push(current);
current = current.next;
}
// 再次遍历链表,弹栈判断
current = head;
while (current != null) {
if (current.val !== stack.pop().val) {
return false
}
current = current.next;
}
return true
}
2.使用字符串反转判断(暴力解决),遍历一次单链表后,我们可以将链表中的字符串提取出来,拼接成一个字符串,然后使用字符反转进行回文判断
function isPalindrome = function(head){
// 2.使用字符串反转判断
if (head === null || head.next === null) {
return true
}
let str = '',
current = head;
//遍历链表,拼接字符串
while(current !== null){
str += current.val;
current = current.next;
}
if(str === Array.from(str).reverse().join('')){
return true
}else{
return false
}
}
3.使用快慢指针,空间复杂度为O(1),定义两个指针(fast、slow),遍历链表,慢指针slow每次移动一步,fast每次移动两步。当遍历结束之后,慢指针正好指向链表的中间,然后从该节点开始对后半部分链表进行反转。然后再次遍历,依次比对
function isPalindrome = function(head) {
if (head === null || head.next === null) {
return true
}
// 3.使用快慢指针
let fast = head,
slow = head,
current = head;
// 遍历链表,移动快慢指针
while (fast.next !== null && fast.next.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
// 此时当快指针移动到末端时,慢指针移动到中间,反转慢指针之后的链表
let reverseListHead = reverseList(slow);
// 遍历链表,判断两个链表是否相等
while (current !== null && reverseListHead !== null) {
if (current.val !== reverseListHead.val) {
return false
}
current = current.next;
reverseListHead = reverseListHead.next;
}
return true;
}
//反转链表
function reverseList(current) {
let pre = null,
curr = current;
while (curr != null) {
let nextNode = curr.next;
curr.next = pre;
pre = curr;
curr = nextNode;
}
return pre;
}
总结
判断链表是否回文是面试中的常考题,主要的思想就是对链表进行反转,遍历比对。使用快慢指针可以使得空间复杂度为O(1),不需要额外使用其他类似数组等数据结构,对于字符串的回文可以将它转换成数组,然后进行反转比对。
本文介绍了回文结构的概念,并详细阐述了使用JavaScript判断单链表是否为回文的四种方法,包括字符串类型和链表类型的解决方案,如字符串反转比对、栈辅助判断、双指针法以及链表反转比对。这些方法各有优劣,适用于不同的场景。
563

被折叠的 条评论
为什么被折叠?



