-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrial.java
More file actions
26 lines (22 loc) · 741 Bytes
/
trial.java
File metadata and controls
26 lines (22 loc) · 741 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
import java.util.*;
public class trial {
public static String longestCommonPrefix(String[] v) {
if (v == null || v.length == 0)
return "";
StringBuilder ans = new StringBuilder();
Arrays.sort(v);
String first = v[0];
String last = v[v.length - 1];
for (int i = 0; i < Math.min(first.length(), last.length()); i++) {
if (first.charAt(i) != last.charAt(i)) {
return ans.toString();
}
ans.append(first.charAt(i));
}
return ans.toString();
}
public static void main(String[] args) {
String[] words = { "apple", "app", "apes", };
System.out.println(longestCommonPrefix(words));
}
}