美文网首页
字符串系列--回文

字符串系列--回文

作者: HongMok | 来源:发表于2017-06-08 00:36 被阅读0次

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;
    }

相关文章

  • 字符串系列--回文

    1.回文字符串 回文,英文palindrome,指一个顺着读和反过来读都一样的字符串,比如madam、我爱我,这样...

  • C# 判断字符串是否是回文字符串(单链表)

    回文字符串: ABCDCBA ABCDDCBA 两种都属于回文字符串; 如何判断一个字符串是否是否回文: 使用快慢...

  • leecode刷题(15)-- 验证回文字符串

    leecode刷题(15)-- 验证回文字符串 验证回文字符串 给定一个字符串,验证它是否是回文串,只考虑字母和数...

  • Design & Coed 1: 检查回文字符串

    案例:检查回文字符串 Check for Palindromes 如果给定的字符串是回文,返回true,反之,返回...

  • 字符串问题合集

    1. 验证回文串 题目描述: 输入一个字符串,只关注字母和数字,判断字符串是否为回文串。空字符串也可以认为是回文串...

  • freecodecamp算法思路记录

    Check for Palindromes 检查回文字符串如果给定的字符串是回文,返回true,反之,返回fals...

  • 字符串常见问题

    找出字符串中出现最多的字符 字符串拼接 判断一个字符串是回文字符串,如 abcdcba是回文字符串, abcdcb...

  • Leetcode-214-Shortest Palindrome

    在给定字符串前面添加若干字符使得字符串变成回文字符串,问回文字符串中最短的字符串是什么。 这题的思路很简单,就是找...

  • 文章收藏

    iOS面试题系列之常见算法 排序算法整理 字符串【3】最长回文子串【3】最长无重复子串【1*】字符串转数字【4】K...

  • 最长回文子串

    最长回文子串——Manacher 算法 1. 问题定义 最长回文字符串问题:给定一个字符串,求它的最长回文子串长度...

网友评论

      本文标题:字符串系列--回文

      本文链接:https://www.haomeiwen.com/subject/uvbafxtx.html