2021-06-19 判断一个链表是不是回文结构

给定一个链表,请判断该链表是否为回文结构。
利用快慢指针,快指针的速度是慢指针速度的两倍,当快指针到达链表尾部的时候,慢指针到达链表的中部,同时将慢指针的值进栈,特别注意,如果链表的长度是奇数时,在比较之前要调整一次慢指针的位置。

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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值