-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem14.java
33 lines (32 loc) · 875 Bytes
/
Problem14.java
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
class Problem14 {
public static void main(String[] args) {
Problem14 p = new Problem14();
String[] list = {""};
System.out.println(p.longestCommonPrefix(list));
}
public String longestCommonPrefix(String[] strs) {
int pos = 0;
boolean flag = true;
String prefix = "";
if (strs.length <= 0) {
return prefix;
}
while (pos >= 0 && pos < strs[0].length()){
prefix = strs[0].substring(0, pos+1);
for (String str : strs) {
if (!str.startsWith(prefix)) {
flag = false;
break;
}
}
if (!flag) {
break;
}
pos++;
}
if (pos <= 0) {
return "";
}
return strs[0].substring(0, pos);
}
}