-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
30 lines (29 loc) · 922 Bytes
/
Copy pathLongestCommonPrefix.java
File metadata and controls
30 lines (29 loc) · 922 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
/**
* Longest Common Prefix http://oj.leetcode.com/problems/longest-common-prefix/
*
* Write a function to find the longest common prefix string amongst an array of strings.
*
* @author joshluo
*
* Really easy problem.
*/
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
assert (strs != null);
if (strs.length == 0)
return "";
String longest = strs[0];
for (String str : strs) {
int i = 0;
while (i < Math.min(longest.length(), str.length())) {
if (longest.charAt(i) != str.charAt(i))
break;
i++;
}
longest = longest.substring(0, i);
}
return longest;
}
}