Possible Duplicate:
Find common prefix of strings
Let's say I have an array of strings. The array has at least two elements, and possibly more. Each string in the array has at least two characters, and possibly more, and at least the first character of every string is the same.
Given said string array, what's the most efficient way to determine the longest prefix shared across all strings?
For example, given ['cowgirl', 'cowboy'], the common prefix is cow. Or, given ['a', 'abs', apples'], the common prefix is a.
I think the simplest algorithm, and perhaps the most efficient, is to just examine the words in sequence, comparing the longest common prefix so far to each word to determine how much of it you can keep. Use the first string as the initial prefix.
EDIT: Here's some Javascript code that does the work:
function findLongestPrefix(list) {
var prefix = list[0];
var prefixLen = prefix.length;
for (var i = 1; i < list.length && prefixLen > 0; i++) {
var word = list[i];
// The next line assumes 1st char of word and prefix always match.
// Initialize matchLen to -1 to test entire word.
var matchLen = 0;
var maxMatchLen = Math.min(word.length, prefixLen);
while (++matchLen < maxMatchLen) {
if (word.charAt(matchLen) != prefix.charAt(matchLen)) {
break;
}
}
prefixLen = matchLen;
}
return prefix.substring(0, prefixLen);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With