【问题标题】:How do I use union find data structure to group Strings?如何使用联合查找数据结构对字符串进行分组?
【发布时间】:2022-04-09 13:20:41
【问题描述】:

我一直在使用 Union-Find(不相交集)来解决很多图形问题,并且知道它是如何工作的。但我几乎总是将这种数据结构与整数或数字一起使用。在解决this leetcode problem 时,我需要对字符串进行分组,并且我正在考虑为此使用 Union-Find。但我不知道如何将它与字符串一起使用。寻找建议。

【问题讨论】:

  • 建议:不要对字符串本身做union-find,而是在字符串的索引上做。
  • 我最终还是这样做了,但我想知道是否必须将这种结构与字符串一起使用,应该采用什么方法?
  • Here 是一个通用实现。
  • 您可以使用哈希表而不是数组来实现标准的基于数组的联合查找数据结构,以将节点映射到它们的父节点。哈希表中的键可以是任何可哈希类型。

标签: data-structures union-find


【解决方案1】:

TLDR:使用与整数/数字相同的联合查找代码,但使用哈希映射而不是数组来存储联合查找中每个元素的父级。这种方法可以推广到可以存储在哈希映射中的任何数据类型,而不仅仅是字符串,即在下面的代码中,两个无序映射可能具有字符串或整数以外的其他内容作为键。

class UnionFind {
public: 
    string find(string s) { 
        string stringForPathCompression = s; 
        while(parent[s] != s) s = parent[s];
        
        // The following while loop implements what is known as path compression, which reduces the time complexity. 
        while(stringForPathCompression != s) { 
            string temp = parent[stringForPathCompression]; 
            parent[stringForPathCompression] = s; 
            stringForPathCompression = temp; 
        }
        return s; 
    }
    void unify(string s1, string s2) {
        string rootS1 = find(s1), rootS2 = find(s2); 
        if(rootS1 == rootS2) return; 
        
        // we unify the smaller component to the bigger component, thus preserving the bigger component. 
        // this is known as union by size, and reduces the time complexity
        if(sz[rootS1] < sz[rootS2]) parent[rootS1] = rootS2, sz[rootS2] += sz[rootS1]; 
        else parent[rootS2] = rootS1, sz[rootS1] += sz[rootS2];         
    }
private: 
    // If we were storing numbers in our union find, both of the hash maps below could be arrays
    unordered_map<string, int> sz; // aka size.
    unordered_map<string, string> parent; 
};

【讨论】:

    【解决方案2】:

    Union Find 并不真正关心对象中的数据类型。您可以决定在主代码中联合哪些字符串,然后联合找到它们的代表值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2015-01-11
      • 2021-07-30
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      相关资源
      最近更新 更多