使用键查找值,反之亦然

本文关键字:反之亦然 查找 | 更新日期: 2023-09-27 18:19:52

首先,为这个讨厌的标题道歉。我稍后会改正的。

我有一些数据如下,

"BOULEVARD","BOUL","BOULV", "BLVD"

我需要一个O(1)的数据结构来查找其他单词中的任何一个。例如,如果我使用字典,我需要像这样存储这些键/值,这对我来说很奇怪,

abbr.Add("BLVD", new List<string> { "BOULEVARD","BOUL","BOULV", "BLVD" });
abbr.Add("BOUL", new List<string> { "BOULEVARD", "BOUL", "BOULV", "BLVD" });
abbr.Add("BOULV", new List<string> { "BOULEVARD", "BOUL", "BOULV", "BLVD" });
abbr.Add("BOULEVARD", new List<string> { "BOULEVARD", "BOUL", "BOULV", "BLVD" });

使用哪种数据结构来保持这些数据适合我的查询条件?

提前感谢

使用键查找值,反之亦然

创建两个HashMap-一个将单词映射到一个组号。另一个将组号映射到单词列表中。这样可以节省一些内存。
Map<String, Integer> - Word to Group Number
Map<Integer, List<String>> - Group Number to a list of words

您需要两次O(1)查找——首先获取组号,然后根据组号获取单词列表。

假设缩写是Dictionary<String, IEnumerable<String>>,则可以使用以下函数:

public static void IndexAbbreviations(IEnumerable<String> abbreviations) {
    for (var a in abbreviations)
        abbr.Add(a, abbreviations);
}

这将用提供的缩写列表填充字典,这样当在字典中查找到任何缩写时。它比您提供的示例代码稍微好一点,因为我没有为每个值创建一个新对象。

从文档中,"使用关键字检索值非常快,接近O(1),因为Dictionary(Of TKey,TValue)类是作为哈希表实现的。"

字典的选择对我来说很好。如上所述,你应该使用相同的列表在字典中引用。代码可能是这样的:

var allAbrList = new List<List<string>>
                 {
                    new List<string> {"BOULEVARD", "BOUL", "BOULV", "BLVD"},
                    new List<string> {"STREET", "ST", "STR"},
                    // ...
                 };
var allAbrLookup = new Dictionary<string, List<string>>();
foreach (List<string> list in allAbrList)
{
    foreach (string abbr in list)
    {
        allAbrLookup.Add(abbr, list);
    }
}

最后一部分可以转换为LINQ以减少代码,但这样更容易理解。

如果不为每个键创建一个新列表,那么只要数据量不是很大,Dictionary<string, List<string>>就会快速且合理地节省内存。您还可以从重用字符串本身中获得一些额外的好处,尽管优化器可能会为您处理这些问题。

var abbr = new Dictionary<string, List<string>>;
var values = new List<string> { "BOULEVARD","BOUL","BOULV", "BLVD" };
foreach(var aValue in values) abbr.add(value, values);

正如Petar Minchev所说,您可以将列表拆分为组列表和指向该组的键列表。为了简化这一点(在使用中),您可以编写自己的IDictionary实现,并使用Add方法来构建这些组。我试了一下,似乎奏效了。以下是实现的重要部分:

public class GroupedDictionary<T> : IDictionary<T,IList<T>>
{
    private Dictionary<T, int> _keys;
    private Dictionary<int, IList<T>> _valueGroups;
    public GroupedDictionary()
    {
        _keys = new Dictionary<T, int>();
        _valueGroups = new Dictionary<int, IList<T>>();
    }
    public void Add(KeyValuePair<T, IList<T>> item)
    {
        Add(item.Key, item.Value);
    }
    public void Add(T key, IList<T> value)
    {
        // look if some of the values already exist
        int existingGroupKey = -1;
        foreach (T v in value)
        {
            if (_keys.Keys.Contains(v))
            {
                existingGroupKey = _keys[v];
                break;
            }
        }
        if (existingGroupKey == -1)
        {
            // new group
            int newGroupKey = _valueGroups.Count;
            _valueGroups.Add(newGroupKey, new List<T>(value));
            _valueGroups[newGroupKey].Add(key);
            foreach (T v in value)
            {
                _keys.Add(v, newGroupKey);
            }
            _keys.Add(key, newGroupKey);
        }
        else
        {
            // existing group
            _valueGroups[existingGroupKey].Add(key);
            // add items that are new
            foreach (T v in value)
            {
                if(!_valueGroups[existingGroupKey].Contains(v))
                {
                    _valueGroups[existingGroupKey].Add(v);
                }
            }
            // add new keys
            _keys.Add(key, existingGroupKey);
            foreach (T v in value)
            {
                if (!_keys.Keys.Contains(v))
                {
                    _keys.Add(v, existingGroupKey);
                }
            }
        }
    }
    public IList<T> this[T key]
    {
        get { return _valueGroups[_keys[key]]; }
        set { throw new NotImplementedException(); }
    }
}

用法可能如下所示:

var groupedDictionary = new GroupedDictionary<string>();
groupedDictionary.Add("BLVD", new List<string> {"BOUL", "BOULV"}); // after that three keys exist and one list of three items
groupedDictionary.Add("BOULEVARD", new List<string> {"BLVD"}); // now there is a fourth key and the key is added to the existing list instance
var items = groupedDictionary["BOULV"]; // will give you the list with four items

当然,实现整个接口需要做很多工作,但在完成后,它将提供一个封装的类,您不必担心。

我认为没有理由将字典的值部分定义为List<string>对象,但这可能是您的要求。这个答案假设你只想知道这个词是否本质上是"林荫大道"的意思。

我会选择一个值作为"官方"值,并将所有其他值映射到它,如下所示:

        var abbr = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
        abbr.Add("BLVD", "BLVD"); // this line may be optional
        abbr.Add("BOUL", "BLVD");
        abbr.Add("BOULV", "BLVD");
        abbr.Add("BOULEVARD", "BLVD");

或者,您可以为字典的值部分定义一个枚举,如下所示:

    enum AddressLine1Suffix
    {
        Road,
        Street,
        Avenue,
        Boulevard,
    }

        var abbr = new Dictionary<string, AddressLine1Suffix>(StringComparer.CurrentCultureIgnoreCase);
        abbr.Add("BLVD", AddressLine1Suffix.Boulevard);
        abbr.Add("BOUL", AddressLine1Suffix.Boulevard);
        abbr.Add("BOULV", AddressLine1Suffix.Boulevard);
        abbr.Add("BOULEVARD", AddressLine1Suffix.Boulevard);