-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq014_LoggestCommonPrefix.java
More file actions
57 lines (49 loc) · 1.46 KB
/
q014_LoggestCommonPrefix.java
File metadata and controls
57 lines (49 loc) · 1.46 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
57
package leetcode_algorithm;
/**
Write a function to find the longest common prefix string amongst an array of strings.
*/
public class q014_LoggestCommonPrefix {
public static void main(String[] args) {
System.out.println(longestCommonPrefix(new String[]{"a" , "a" , "b"}));
System.out.println(longestCommonPrefix(new String[]{"abca", "abc"}));
System.out.println(longestCommonPrefix(new String[]{"ac", "ac", "a", "a"}));
}
/**
* ½â·¨1(¸öÈ˽ⷨ)
* @param strs
* @return
*/
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for(int i = 0;i< strs[0].length();i++) {
char c = strs[0].charAt(i);
for(int j = 1 ; j < strs.length; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return sb.toString();
}
}
sb.append(c);
}
return sb.toString();
}
/**
* ½â·¨2
*
* @param strs
* @return
*/
public static String longestCommonPrefix2(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
}