The value returned by longestPrefix(array)
could potentially be different for each non-empty subset of your set. Additionally, each string may belong to multiple "groups", depending on what other items are there in a group: for example, if the original list contained some BRIGGS & SON
items, the BRIGGS & STRATTON
items could have been grouped with BRIGGS &
items as well.
最長の共通接頭辞でグループ化として要件を再定義すると、次のように、対の共通接頭辞を計算し、最長の接頭辞を取得してグループ化することができます。
void AddLongest(IDictionary dict, string s, string p) {
string current;
if (!dict.TryGetValue(s, out current) || p.Length > current.Length) {
dict[s] = p;
}
}
var longestPrefix = new Dictionary();
for (int i = 0 ; i != myStrings.Length ; i++) {
for (int j = i+1 ; j != myStrings.Length ; j++) {
var common = FindLongestPrefix(new[] {myStrings[i], myStrings[j]});
AddLongest(longestPrefix, myStrings[i], common);
AddLongest(longestPrefix, myStrings[j], common);
}
}
// Now you can use LINQ to group by the longest common prefix:
var groups = myStrings.GroupBy(s => longestPrefix[s]);