14.最长公共前缀
先以数组的第一个元素为前缀,然后遍历依次获取公共的字符串。
1
class Solution {
2
public String longestCommonPrefix(String[] strs) {
3
if (strs == null || strs.length == 0)
4
return "";
5
String prefix = strs[0];
6
for (int i = 1; i < strs.length && prefix.length() > 0; i++) {
7
prefix = getPrefix(prefix, strs[i]);
8
}
9
return prefix;
10
}
11
public String getPrefix(String prefix, String str) {
12
int length = prefix.length() > str.length() ? str.length() : prefix.length();
13
StringBuilder sb = new StringBuilder();
14
for (int i = 0; i < length; i++) {
15
if (prefix.charAt(i) == str.charAt(i))
16
sb.append(prefix.charAt(i));
17
else
18
return sb.toString();
19
}
20
return sb.toString();
21
}
22
}
Copied!
看到的另外一种思路:
1
class Solution {
2
public String longestCommonPrefix(String[] strs) {
3
if(strs == null || strs.length == 0) return "";
4
String pre = strs[0];
5
int i = 1;
6
while(i < strs.length){
7
while(strs[i].indexOf(pre) != 0)
8
pre = pre.substring(0,pre.length()-1);
9
if(pre.length() == 0)
10
break;
11
i++;
12
}
13
return pre;
14
}
15
}
Copied!
最近更新 28d ago
复制链接