Problem:
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
class Solution {
public:
string findPrefix(string a, string b) {
int size_a = a.size(), size_b = b.size();
int size = min(size_a, size_b);
int commonPrefix = 0;
string sol;
for (int i = 0; i < size; i++) {
if (a[i] == b[i])
commonPrefix++;
else
break;
}
return a.substr(0, commonPrefix);
}
string longestCommonPrefix(vector<string>& strs) {
int size = strs.size();
if (size == 0)
return "";
else if (size == 1)
return strs[0];
else if (size == 2)
return findPrefix(strs[0], strs[1]);
else {
// Recursive approach
/*
vector<string> first, second;
string firstHalf, secondHalf;
for (int i = 0; i < size; i++) {
if ((i % 2) == 0)
first.push_back(strs[i]);
else
second.push_back(strs[i]);
}
firstHalf = longestCommonPrefix(first);
secondHalf = longestCommonPrefix(second);
return findPrefix(firstHalf, secondHalf);
*/
// Iterative approach
string sol = strs[0];
for (int i = 0; i < size; i++) {
sol = findPrefix(strs[i], sol);
}
return sol;
}
}
};
==== Optimized solution ====
// Check vertical
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
class Solution {
public:
string findPrefix(string a, string b) {
int size_a = a.size(), size_b = b.size();
int size = min(size_a, size_b);
int commonPrefix = 0;
string sol;
for (int i = 0; i < size; i++) {
if (a[i] == b[i])
commonPrefix++;
else
break;
}
return a.substr(0, commonPrefix);
}
string longestCommonPrefix(vector<string>& strs) {
int size = strs.size();
if (size == 0)
return "";
else if (size == 1)
return strs[0];
else if (size == 2)
return findPrefix(strs[0], strs[1]);
else {
// Recursive approach
/*
vector<string> first, second;
string firstHalf, secondHalf;
for (int i = 0; i < size; i++) {
if ((i % 2) == 0)
first.push_back(strs[i]);
else
second.push_back(strs[i]);
}
firstHalf = longestCommonPrefix(first);
secondHalf = longestCommonPrefix(second);
return findPrefix(firstHalf, secondHalf);
*/
// Iterative approach
string sol = strs[0];
for (int i = 0; i < size; i++) {
sol = findPrefix(strs[i], sol);
}
return sol;
}
}
};
==== Optimized solution ====
// Check vertical
class Solution {public: string longestCommonPrefix(vector<string> &strs) { if (strs.empty()){return "";} if (strs.size()==1){return strs[0];} for (int i=0;i<strs[0].size();i++){ for (int j=0;j<strs.size()-1;j++){ if (i>=strs[j+1].size() || strs[j][i]!=strs[j+1][i]){ return strs[j].substr(0,i); } } } return strs[0]; }};
No comments:
Post a Comment