遍历 + 维护公共子串

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
class Solution {
/**
* 遍历 + 维护公共子串
*/
public String longestCommonPrefix(String[] strs) {
String ans = strs[0];
for (int i = 1; i < strs.length; i++) {
String str = strs[i];
int index = pubSubStringIndex(ans, str);
// 不存在相同的前缀
if (index == -1) return "";
ans = ans.substring(0, index);
}
return ans;
}

private int pubSubStringIndex(String ori, String dest) {
if (dest.length() < ori.length()) {
String tmp = dest;
dest = ori;
ori = tmp;
}
for (int i = 0; i < ori.length(); i++) {
if (ori.charAt(i) != dest.charAt(i)) {
return i;
}
}
return ori.length();
}
}

Comments
Recent Posts
计算机网络
进程树
进程管理
Categories
Website Info
Article Count :
4
Total Word Count :
14.4k
Unique Visitors :
Page Views :
Last Update :