问题
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: strs = [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
Input: strs = [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Constraints:
- 0 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
思考
最长的共同前缀,所以每个字符从头开始匹配看是不是相同就好了.
方法1
假设最短字符长度为n, 每个字符都只需要最多检查到第n位就可以了.或者直接把最短长度的字符作为起始, 开始遍历.
时间复杂度
O
(
M
∗
N
)
O(M * N)
O(M∗N).
空间复杂度
O
(
N
)
O(N)
O(N).
M:字符串个数
N:最短字符串长度
class Solution {
public String longestCommonPrefix(String[] strs) {
int len = 201;
String res = "";
// 找到最小的len, 以及对应的str
for(String str : strs){
if(str.length() < len){
len = str.length();
res = str;
}
}
for(String str : strs){
for(int i = 0; i < len; i++){
if(str.charAt(i) != res.charAt(i)){
len = i;
res = res.substring(0, len);
break;
}
}
}
return res;
}
}
方法2
方法1是按照字符串来进行遍历.也可以按照位数来进行遍历.
共同前缀, 也就是说如果存在,那么所有的字符串的一定是从第一个字符开始有相同的部分.那么就从第一个字符开始遍历,直到碰到不相同的,或者是长度不够的字符为止.
时间复杂度其实和方法一样,不过省去了很多string的操作.在极大量数据的时候估计会有性能提升.
时间复杂度
O
(
M
∗
N
)
O(M * N)
O(M∗N).
空间复杂度
O
(
N
)
O(N)
O(N).
M:字符串个数
N:最短字符串长度
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String f = strs[0];
for(int i = 0, len = f.length();i < len; i++){
char c = f.charAt(i);
for(int j = 0; j < strs.length; j++){
if(i >= strs[j].length() || c != strs[j].charAt(i)){
return f.substring(0, i);
}
}
}
return f;
}
}