014.Longest Common Prefix

Solution 1: accepted

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
public class Solution {
public String longestCommonPrefix(String[] strs) {
int length = strs.length;
if (length == 0) {
return "";
}
else if (length == 1){
return strs[0];
}
else {
String answer = strs[0];
for (int i = 1; i < length; i++) {
if (answer.equals(""))
break;
else if (strs[i].startsWith(answer)) {
continue;
}
else {
while (!strs[i].startsWith(answer)) {
answer = answer.substring(0, answer.length() - 1);
}
}
}
return answer;
}
}
}