Skip to content

Commit c517b95

Browse files
committed
commit
1 parent 3eb9a19 commit c517b95

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

14. Longest Common Prefix.java

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public String longestCommonPrefix(String[] strs) {
3+
String long_prefix = strs[0]; // Select first string as a longest prefix
4+
5+
// Search for the longest prefix in all strings
6+
for (int idx = 1; idx < strs.length; idx++) {
7+
// Find the longest prefix
8+
while (strs[idx].indexOf(long_prefix) != 0) {
9+
// Decrease string length untill find the prefix
10+
long_prefix = long_prefix.substring(0, long_prefix.length() - 1);
11+
}
12+
13+
// Check if prefix is empty after loop once
14+
if (long_prefix.isEmpty()) break;
15+
}
16+
17+
return long_prefix;
18+
}
19+
}

0 commit comments

Comments
 (0)