first iteration
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
string prefix;
// empty string vector
if (strs.empty()) {
return prefix;
}
int idx=0;
char c;
while (true) {
// get character to be compared from first string
if (idx < strs[0].size()) {
c = strs[0][idx];
} else {
break;
}
// check if all strings has that character in the index
// - break out if either out of length or not same
bool same = true;
for (int i = 1; i < strs.size(); i++) {
if (idx >= strs[i].size() || strs[i][idx] != c) {
same = false;
break;
}
}
// grow prefix if it is same otherwise, break out
if (same) {
prefix.push_back(c);
} else {
break;
}
idx++;
}
return prefix;
}
};
2nd iteration with a little refactor
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
string prefix;
// empty string vector
if (strs.empty()) {
return prefix;
}
int len=0;
while (true) {
char var;
int i = 0;
for (; i < strs.size(); i++) {
// get character to be compared from first string
// could be '\0', but we break out as below
if (i==0) {
var = strs[0][len];
}
// break out if run out of length or character comparision
// failed
if (len == strs[i].size() || strs[i][len] != var) {
break;
}
}
// this means compare with this character failed, break out
// and return whatever we got for prefix
// NOTE: use the fact we early break out from for-loop or not to
// determine if we need continue the check
if (i != strs.size()) {
break;
}
// continue the checkfor longest common prefix
prefix.push_back(var);
len++;
}
return prefix;
}
};