-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14_Longest_Common_Prefix.java
More file actions
38 lines (36 loc) · 1022 Bytes
/
Copy path14_Longest_Common_Prefix.java
File metadata and controls
38 lines (36 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* BRUTE FORCE --> Beats 80%
class Solution {
public String longestCommonPrefix(String[] strs) {
Arrays.sort(strs);
String start = strs[0];
String end = strs[strs.length-1];
int idx = 0;
while(idx < start.length() && idx < end.length()){
if(start.charAt(idx) == end.charAt(idx)){
idx++;
} else {
break;
}
}
return start.substring(0, idx);
}
}
*/
/* OPTIMIZED --> Beats 100% */
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].startsWith(prefix)==false) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
}