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 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z. 所有输入只包含小写字母 a-z 。
方法一:水平扫描法
查找一组字符串的最长公共前缀的简单方法:
![]()
算法:
- 当字符串数组长度为 0 时则公共前缀为空,直接返回
- 令最长公共前缀 ans 的值为第一个字符串,进行初始化
- 遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终结果即为最长公共前缀
- 如果查找过程中出现了 ans 为空的情况,则公共前缀不存在直接返回
复杂度:
- 时间复杂度:O(s),s 为所有字符串的长度之和。最坏的情况下,nn 个字
- 符串都是相同的。算法会将 S1与其他字符串都做一次比较,这样就会进行 S 次字符比较
- 空间:O(1)
代码一:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String ans = strs[0];
for(int i =1;i<strs.length;i++) {
int j=0; //这里 j 必须在外面申明,否则找不到?
for(;j<ans.length() && j < strs[i].length();j++) {
if(ans.charAt(j) != strs[i].charAt(j))
break;
}
ans = ans.substring(0, j);
if(ans.equals(""))
return ans;
}
return ans;
}
}
代码二:
巧妙使用 indexOf 查找前缀,这种方法比第一种时间快很多。相当于这是“减法”,上一种代码是“加法”
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;
}
1万+

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



