-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
38 lines (32 loc) · 1004 Bytes
/
LongestCommonPrefix.java
File metadata and controls
38 lines (32 loc) · 1004 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
/**
* Leet code problem, #14: Longest Common Prefix
* https://leetcode.com/problems/longest-common-prefix/
*/
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = { "flower", "flow", "flight" };
System.out.println(longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder("");
if (strs.length == 0) {
return sb.toString();
}
int minLength = Integer.MAX_VALUE;
for (String str : strs) {
if (str.length() < minLength) {
minLength = str.length();
}
}
for (int i = 0; i < minLength; i++) {
char c = strs[0].charAt(i);
for (String str : strs) {
if (str.charAt(i) != c) {
return sb.toString();
}
}
sb.append(c);
}
return sb.toString();
}
}