题目:
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
.
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0) return "";
string temp = strs[0];
for(int i = 1; i < strs.size(); i++){
while(strs[i].find(temp) != 0){
temp = temp.substr(0, temp.size() - 1);
}
}
return temp;
}
};
Solution
Approach #1 (Horizontal scanning)
Intuition
For a start we will describe a simple way of finding the longest prefix shared by a set of strings LCP(S_1 \ldots S_n)LCP(S1…Sn). We will use the observation that :
LCP(S_1 \ldots S_n) = LCP(LCP(LCP(S_1, S_2),S_3),\ldots S_n)LCP(S1…Sn)=LCP(LCP(LCP(S1,S2),S3),…Sn)
Algorithm
To employ this idea, the algorithm iterates through the strings [S_1 \ldots S_n][S1…Sn], finding at each iteration iithe longest common prefix of strings LCP(S_1 \ldots S_i)LCP(S1…Si) When LCP(S_1 \ldots S_i)LCP(S1…Si) is an empty string, the algorithm ends. Otherwise after nn iterations, the algorithm returns LCP(S_1 \ldots S_n)LCP(S1…Sn).
Figure 1. Finding the longest common prefix (Horizontal scanning)
Java
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; }
Complexity Analysis
- Time complexity : O(S)O(S) , where S is the sum of all characters in all strings.
In the worst case all n