【算法】JAVA實現快慢指針法 單鏈表實現判斷水仙花字符串

package data_structure;

/**
 * author: cdfuhuichao
 * date: 2019/3/5 18:11
 * description: 使用單鏈表實現 判斷水仙花字符串
 */
public class SXHString {

    public static void main(String[] args) {
        System.out.println(check("上海自來水來自海上"));
        System.out.println(check("上海自來來自海上"));
        System.out.println(check("上"));

    }

    // 打印鏈表
    public static String printNode(Node n) {
        StringBuilder sb = new StringBuilder();
        for (; ; ) {
            sb.append(n.item.toString());
            if (!n.hasNext()) {
                break;
            }
            n = n.next;
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    private static class Node<E> {
        E item;
        Node<E> next;

        Node(E element) {
            this.item = element;
        }

        public boolean hasNext() {
            return next != null;
        }

    }

    public static Node init(String s) {
        // 初始化鏈表
        Node old = new Node(s.charAt(0));
        Node current = old;
        for (int i = 1; i < s.length(); i++) {
            current = current.next = new Node(s.charAt(i));
        }
        return old;
    }

    public static boolean check(String s) {

        if (s.length() < 2) {
            return true;
        }

        // 初始化鏈表
        Node old = init(s);

        // 快慢指針
        int m = 0;
        Node current = old;
        Node prev = null;
        Node next = null;
        Node newone1 = null;
        Node newone2 = null;
        for (; ; ) {
            boolean hasNext = current.hasNext();

            next = current.next;

            // 判斷奇偶,快指針到終點前,將鏈表逆序
            if ((s.length() % 2 == 0 && m < s.length()) || (s.length() % 2 != 0 && m < s.length() - 1)) {
                if (prev == null) {
                    current.next = null;
                } else {
                    current.next = prev;
                }
            } else {
                // 快指針到終點後,將前半截鏈表和後半截鏈表拆分
                if (m == s.length() - 1) {
                    current = next;
                }
                newone1 = prev;
                newone2 = current;
                break;
            }

            m += 2;
            prev = current;
            current = next;

            if (!hasNext) {
                break;
            }
        }

        if (newone1 == null || newone2 == null) {
            return false;
        }
        String ss1 = printNode(newone1);
        String ss2 = printNode(newone2);

        return ss1.equals(ss2);
    }

}

歡迎指出不足和錯誤,謝謝。java

相關文章
相關標籤/搜索