Skip to content

Commit 2f03934

Browse files
committed
Updated longest common prefix
1 parent a8fdfcb commit 2f03934

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

Easy/LongestCommonPrefix.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ public static void main(String[] args) {
1111
}
1212

1313
/**
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
1518
*/
1619
public static String longestCommonPrefix(String[] strs) {
1720
for (int i = strs.length - 2; i >= 0 ; i--) {
@@ -20,6 +23,13 @@ public static String longestCommonPrefix(String[] strs) {
2023
return strs[0];
2124
}
2225

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+
*/
2333
private static String commonPrefix(String a, String b) {
2434
StringBuilder pref = new StringBuilder();
2535
int lenA = a.length();
@@ -60,4 +70,4 @@ public String longestCommonPrefix(String[] strs) {
6070

6171
return word.substring(0, prefixLength);
6272
}
63-
}
73+
}

0 commit comments

Comments
 (0)