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 item; Node 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); }}
欢迎指出不足和错误,谢谢。