-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
88 lines (82 loc) · 2.87 KB
/
LongestCommonPrefix.java
File metadata and controls
88 lines (82 loc) · 2.87 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package explore.array;
/**
* @author :DengSiYuan
* @date :2019/10/29 21:25
* @desc : 14.最长公共前缀
* 【题意】
* 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
* 【示例】
* 示例 1:
* 输入: ["flower","flow","flight"]
* 输出: "fl"
* 示例 2:
* 输入: ["dog","racecar","car"]
* 输出: ""
* 解释: 输入不存在公共前缀。
* 【说明】
* 所有输入只包含小写字母 a-z 。
*/
public class LongestCommonPrefix {
/**
* 【想法】
* 1、首先判断传入的字符串数组是否为空,若为空直接返回""
* 2、找到最短的字符串变成字符数组
* 3、遍历最短的字符串,判断在其他中按位进行比对,遇到不同就立即跳出,进行返回
* @param strs
* @return
*/
public String longestCommonPrefix1(String[] strs) {
if (strs == null ||strs.length == 0 ){
return "";
}
String minxStr = strs[0];
for (String str : strs) {
minxStr = (str.length() > minxStr.length() ? minxStr : str);
}
StringBuilder stringBuilder = new StringBuilder("");
char[] chars = minxStr.toCharArray();
for (int i = 0; i < chars.length; i++) {
boolean status = false;
for (String str : strs) {
if (str.toCharArray()[i] != chars[i]){
status = true;
break;
}
}
if (!status){
stringBuilder.append(chars[i]);
}else {
break;
}
}
return stringBuilder.toString();
}
public String longestCommonPrefix2(String[] strs) {
if (strs.length==0) {
return "";
}
String prefix=strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix)!=0) {
prefix=prefix.substring(0, prefix.length()-1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
public static void main(String[] args) {
LongestCommonPrefix prefix = new LongestCommonPrefix();
long start = System.nanoTime();
String result = prefix.longestCommonPrefix1(new String[]{"flower","flow","flight"});
long end = System.nanoTime();
System.out.println(result);
System.out.println("运行时间:" + (end - start) / 1000000.0 + "ms");
start = System.nanoTime();
result = prefix.longestCommonPrefix2(new String[]{"flower","flow","flight"});
end = System.nanoTime();
System.out.println(result);
System.out.println("运行时间:" + (end - start) / 1000000.0 + "ms");
}
}