Write a program to return the longest prefix string in a container containing vector in the string, if "" is not returned
INPUT: [ "Flower", "Flow", "Flight"]
Output: FL
input:[“dog”,“racecar”,“car”]
output:""
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0 || find(strs.begin(), strs.end(), "") != strs.end())
return "";
int i, j;
sort(strs.begin(), strs.end(), [](string a, string b) {return a.size() < b.size(); });
for (i = 0; i < strs[0].size(); ++i) {
for (j = 1; j < strs.size(); ++j) {
if (strs[0].at(i) != strs[j].at(i)) {
return (i - 1 >= 0) ? strs[0].substr(0, i) : "";
}
}
}
return strs[0];
}
Idea: turn relatively violence iteration, the first and back, if you have the same prefix string to the next, if there is no direct return on a prefix string (that is conditional loop to proceed is to have the same prefix string)
most loop iteration will be mn times worse case, m is the shortest string length of a vector, n being the vector size, so O (mN)
Another approach, the horizontal scanning, for example { "leetcode", "leet" , "lee"}, compare the first two elements obtained prefix = "leet", then a comparison with the current prefix obtained le lower, so
java code
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;
}
The worst case is O (S), S is the total of all the string length