给定一个链表,请判断该链表是否为回文结构。
利用快慢指针,快指针的速度是慢指针速度的两倍,当快指针到达链表尾部的时候,慢指针到达链表的中部,同时将慢指针的值进栈,特别注意,如果链表的长度是奇数时,在比较之前要调整一次慢指针的位置。
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
if(head==null||head.next==null)
return true;
ListNode slow=head;
ListNode fast=head;
Stack<Integer> stack=new Stack<>();
while(fast!=null&&fast.next!=null){
stack.push(slow.val);
slow=slow.next;
fast=fast.next.next;
}
if(fast!=null&&fast.next==null){
slow=slow.next; //如果链表长度是奇数,那么12321,将slow由3指向3后面的2
}
while(!stack.isEmpty()){
if(stack.pop()!=slow.val){
return false;
}
slow=slow.next;
}
return true;
}
}
判断回文字符串
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param str string字符串 待判断的字符串
* @return bool布尔型
*/
public boolean judge (String str) {
// write code here
Stack<Character> res=new Stack<>();
int len=str.length();
int mid=len/2;
for(int i=0;i<mid;i++){
res.push(str.charAt(i));
}
int j=len%2==0?mid:mid+1;
for(int i=j;i<len;i++){
if(str.charAt(i)!=res.pop())
return false;
}
return true;
}
}
public boolean judge (String str) {
// write code here
if(str.isEmpty()||str==null) return false;
char[] charArray = str.toCharArray();
int i = 0;
int j = charArray.length - 1;
while(i<j){
if(charArray[i]==charArray[j]){
i++;
j--;
}else{
return false;
}
}
return true;
}