字符串系列--回文

1.回文字符串

回文,英文palindrome,指一个顺着读和反过来读都一样的字符串,比如madam、我爱我,这样的短句在智力性、趣味性和艺术性上都颇有特色,中国历史上还有很多有趣的回文诗。
那么,我们的第一个问题就是:判断一个字串是否是回文?

思路:
前后两边逐个对比


2. 单向链表判断回文

判断一条单向链表是不是“回文”

思路:
1.用快慢指针,定位到中间节点
2.把前半段逆转方向
3.注意单个节点的链表,奇偶长度的链表

    private static boolean isPalindromeList( Node node ){
        if( node == null ){
            return false;
        }
        if( node.next == null ){
            return true;
        }
        Node slow = node;
        Node fast = node;
        boolean isDouble = true;
        while( true ){
            if( fast.next == null ){
                isDouble = false;
                break;
            }
            fast = fast.next;
            if( fast.next == null )
            {
                break;
            }
            else{
                fast = fast.next;
            }
            slow = slow.next;//slow每次走一步
        }
        //这是slow就是中点
        Node center = slow;
        
        Node head2 = center.next;
        
        //把前半段,逆转顺序,如果是奇数,则前半段不包含slow;如果是偶数,则前半段包含slow
        Node head = node;
        Node curr = head.next;
        Node temp;
        head.next = null;
        while( curr != null ){
            
            if( isDouble ){
                if( head == center ){
                    break;//偶数长度,末尾
                }
            }
            else if( curr == center ){
                break;//奇数长度,末尾
            }
            
            temp = head;
            head = curr;
            curr = curr.next;
            head.next = temp;
        }
        
        Node head1 = head;
        
        while( head1 != null ){
            if( head1.value != head2.value ){
                return false;
            }
            head1 = head1.next;
            head2 = head2.next;
        }
        
        return true;
    }

你可能感兴趣的:(字符串系列--回文)