LeetCode 14. Longest Common Prefix
Description
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example

Note
All given inputs are in lowercase letters a-z.
Code
- java
class Solution {
public String longestCommonPrefix(String[] strs) {
int len = strs.length;
if(len == 0) return "";
int commonLength = 0;
int minLength = strs[0].length();
for(int i = 1; i < len; i++) {
minLength = Math.min(minLength, strs[i].length());
}
for(; commonLength < minLength; commonLength++) {
char ch = strs[0].charAt(commonLength);
boolean same = true;
for(int i = 1; i < len; i++) {
if(strs[i].charAt(commonLength) != ch) {
same = false;
break;
}
}
if(!same) break;
}
return strs[0].substring(0, commonLength);
}
}
- Official solution1
- 按两个之间比较后得到的结果与下一个字符串继续比较。
public String longestCommonPrefix(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;
}
- Official Solution2:Vertical scanning
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
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 strs[0].substring(0, i);
}
}
return strs[0];
}
}
Conclusion
- 有很多种解法,比如二分,归并等
本文详细解析了LeetCode第14题“最长公共前缀”的多种解法,包括直接比较、垂直扫描等,提供了清晰的代码示例,帮助读者理解和掌握此题的解决策略。

157

被折叠的 条评论
为什么被折叠?



