-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
33 lines (29 loc) · 1.3 KB
/
Copy pathLongestCommonPrefix.java
File metadata and controls
33 lines (29 loc) · 1.3 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
// Write a function to find the longest common prefix string amongst an array of strings.
// If there is no common prefix, return an empty string ""
// See: https://leetcode.com/problems/longest-common-prefix/
package leetcode.string;
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
StringBuilder lcp = new StringBuilder("");
if (strs.length == 0) {
return lcp.toString();
}
for (int i = 0; ;i++) {
for (String s : strs) {
if (i == s.length() || s.charAt(i) != strs[0].charAt(i)) {
return lcp.toString();
}
};
lcp.append(strs[0].charAt(i));
}
}
public static void main(String... args) {
LongestCommonPrefix sln = new LongestCommonPrefix();
System.out.println(sln.longestCommonPrefix(new String[] {"flower","flow","flight"}));
System.out.println(sln.longestCommonPrefix(new String[] {"ab","bc","de"}));
System.out.println(sln.longestCommonPrefix(new String[] {"ab"}));
System.out.println(sln.longestCommonPrefix(new String[] {""}));
System.out.println(sln.longestCommonPrefix(new String[] {"ab", "abc"}));
System.out.println(sln.longestCommonPrefix(new String[] {}));
}
}