forked from team-codebug/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14LongestCommonPrefix.java
More file actions
42 lines (32 loc) · 938 Bytes
/
14LongestCommonPrefix.java
File metadata and controls
42 lines (32 loc) · 938 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
39
40
41
42
class Solution {
public String getCommonPrefix(String s1, String s2) {
if (s2.length() < s1.length()) {
return getCommonPrefix(s2, s1);
}
// "", "apple"
if (s1.length() == 0 || s2.length() == 0) {
return "";
}
int i = 0;
while (i < s1.length()) {
if (s1.charAt(i) != s2.charAt(i)) {
return s1.substring(0, i);
}
i += 1;
}
return s1;
}
public String longestCommonPrefix(String[] strs) {
if (strs == null) {
return "";
}
if (strs.length == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i += 1) {
prefix = getCommonPrefix(prefix, strs[i]);
}
return prefix;
}
}