C# or JavaScript: Determining common prefix in strings [duplicate]
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);
}
You can check these resources about finding the longest common prefix substring between two strings or more.. even if the Algorithms are presented in other languages I am sure you can adapt one to JavaScript.
Find common prefix of strings
Algorithm Implementation/Strings/Longest common substring
精彩评论