-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
56 lines (45 loc) · 1.35 KB
/
LongestCommonPrefix.java
File metadata and controls
56 lines (45 loc) · 1.35 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package string;
import java.util.Arrays;
/**
* Description: https://leetcode.com/problems/longest-common-prefix
* Difficulty: Easy
*/
public class LongestCommonPrefix {
/**
* Time complexity: O(n * m)
* Space complexity: O(m)
*/
public String longestCommonPrefix(String[] strs) {
if (strs.length == 1) return strs[0];
String first = strs[0];
StringBuilder result = new StringBuilder();
for (int i = 0; i < first.length(); i++) {
for (int j = 1; j < strs.length; j++) {
if (i >= strs[j].length() || first.charAt(i) != strs[j].charAt(i)) {
return result.toString();
}
}
result.append(first.charAt(i));
}
return result.toString();
}
/**
* Time complexity: O(nlog n)
* Space complexity: O(m)
*/
public String longestCommonPrefixViaSorting(String[] strs) {
if (strs.length == 1) return strs[0];
Arrays.sort(strs);
String first = strs[0];
String last = strs[strs.length - 1];
int counter = 0;
for (int i = 0; i < first.length(); i++) {
if (first.charAt(i) == last.charAt(i)) {
counter++;
} else {
break;
}
}
return first.substring(0, counter);
}
}