字符串系列--回文

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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 字符串回文判断 题目描述: 回文,英文palindrome,指一个顺着读和反过来读都一样的字符串,比如madam、...
    MinoyJet阅读 3,801评论 0 2
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,942评论 2 36
  • 1.把二元查找树转变成排序的双向链表 题目: 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。 要求不...
    曲终人散Li阅读 3,371评论 0 19
  • 最长回文子串——Manacher 算法 1. 问题定义 最长回文字符串问题:给定一个字符串,求它的最长回文子串长度...
    林大鹏阅读 2,801评论 0 6
  • 1 回文识别基础 回文通俗地将就是把一个句子或者字符串正过来反过来读都是一样的.比如123321就是一个回文. 识...
    少冰三hun甜阅读 733评论 0 0