File tree Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Original file line number Diff line number Diff line change @@ -11,7 +11,10 @@ public static void main(String[] args) {
11
11
}
12
12
13
13
/**
14
- * loop backwards and overwrite previous word with prefix
14
+ * Find common prefix one by one from the end of the input string array
15
+ * Overwrite the ith string with common prefix result
16
+ * Thus space usage is reduced
17
+ * Return first in group
15
18
*/
16
19
public static String longestCommonPrefix (String [] strs ) {
17
20
for (int i = strs .length - 2 ; i >= 0 ; i --) {
@@ -20,6 +23,13 @@ public static String longestCommonPrefix(String[] strs) {
20
23
return strs [0 ];
21
24
}
22
25
26
+ /**
27
+ * Get length of two strings
28
+ * Loop over each char till one length runs out
29
+ * If same char, append it to result
30
+ * If not same, break
31
+ * Return result
32
+ */
23
33
private static String commonPrefix (String a , String b ) {
24
34
StringBuilder pref = new StringBuilder ();
25
35
int lenA = a .length ();
@@ -60,4 +70,4 @@ public String longestCommonPrefix(String[] strs) {
60
70
61
71
return word .substring (0 , prefixLength );
62
72
}
63
- }
73
+ }
You can’t perform that action at this time.
0 commit comments