From 47ff0ddf6db8f9836fa4e3a725559223d2752656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B7=A6=E7=A8=8B=E4=BA=91?= Date: Tue, 2 Feb 2021 19:06:04 +0800 Subject: [PATCH] modify code --- src/class27/Code01_KMP.java | 16 ++++++---------- src/class27/Code02_TreeEqual.java | 5 ----- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/class27/Code01_KMP.java b/src/class27/Code01_KMP.java index d8dce70..653b103 100644 --- a/src/class27/Code01_KMP.java +++ b/src/class27/Code01_KMP.java @@ -1,23 +1,21 @@ package class27; public class Code01_KMP { - // O(N) + public static int getIndexOf(String s, String m) { if (s == null || m == null || m.length() < 1 || s.length() < m.length()) { return -1; } char[] str = s.toCharArray(); char[] match = m.toCharArray(); - int x = 0; // str中当前比对到的位置 - int y = 0; // match中当前比对到的位置 - // M M <= N O(M) - int[] next = getNextArray(match); // next[i] match中i之前的字符串match[0..i-1] - // O(N) + int x = 0; + int y = 0; + int[] next = getNextArray(match); while (x < str.length && y < match.length) { if (str[x] == match[y]) { x++; y++; - } else if (next[y] == -1) { // y == 0 + } else if (next[y] == -1) { x++; } else { y = next[y]; @@ -26,7 +24,6 @@ public class Code01_KMP { return y == match.length ? x - y : -1; } - // M O(M) public static int[] getNextArray(char[] match) { if (match.length == 1) { return new int[] { -1 }; @@ -35,10 +32,9 @@ public class Code01_KMP { next[0] = -1; next[1] = 0; int i = 2; - // cn代表,cn位置的字符,是当前和i-1位置比较的字符 int cn = 0; while (i < next.length) { - if (match[i - 1] == match[cn]) { // 跳出来的时候 + if (match[i - 1] == match[cn]) { next[i++] = ++cn; } else if (cn > 0) { cn = next[cn]; diff --git a/src/class27/Code02_TreeEqual.java b/src/class27/Code02_TreeEqual.java index d9453a5..657373a 100644 --- a/src/class27/Code02_TreeEqual.java +++ b/src/class27/Code02_TreeEqual.java @@ -14,23 +14,19 @@ public class Code02_TreeEqual { } } - // big做头节点的树,其中是否有某棵子树的结构,是和small为头的树,完全一样的 public static boolean containsTree1(Node big, Node small) { if (small == null) { return true; } - // small != null if (big == null) { return false; } - // big!=null small!=null if (isSameValueStructure(big, small)) { return true; } return containsTree1(big.left, small) || containsTree1(big.right, small); } - // head1为头的树,是否在结构对应上,完全和head2一样 public static boolean isSameValueStructure(Node head1, Node head2) { if (head1 == null && head2 != null) { return false; @@ -44,7 +40,6 @@ public class Code02_TreeEqual { if (head1.value != head2.value) { return false; } - // head1.value == head2.value return isSameValueStructure(head1.left, head2.left) && isSameValueStructure(head1.right, head2.right); }