/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//方法一: 借助数组 空间复杂度O(n) 时间复杂度O(n)
int len = 0 ;
ListNode yummy = head ;
while(head!=null){
len++;
head = head.next;
}
int[] ints = new int[len];
for(int i = 0 ; i < len ; i++){
ints[i] = yummy.val;
yummy = yummy.next;
}
int start = 0 ;
int end = len-1;
while(start <= end && ints[start] == ints[end]){
start++;
end-- ;
}
if(start>end) return true;
return false;
//------------------------------------------------------------------------------------------------------
//方法二: 借助临时变量 将回文链表转化为回文字符串判断 空间复杂度O(1) 时间复杂度O(n)
String temp = new String("");
String ans = new String("");
while(head!=null){
StringBuilder sb = new StringBuilder(head.val+"");
//注意是整个数字的比较 而不是每个字母的比较,所以要保证每个节点内部的数字顺序是不变的
//原理,负负得正 反转两次保证内部节点的数字大小不变
temp += sb.reverse().toString();
ans += head.val;
head = head.next;
}
StringBuilder sb = new StringBuilder(temp);
String ans2 = sb.reverse().toString();
return ans.equals(ans2);
}
}
验证回文链表
最新推荐文章于 2023-07-28 17:28:26 发布