首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用联合查找数据结构对字符串进行分组?

如何使用联合查找数据结构对字符串进行分组?
EN

Stack Overflow用户
提问于 2020-01-21 21:09:33
回答 1查看 493关注 0票数 0

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

EN

回答 1

Stack Overflow用户

发布于 2021-11-14 08:33:45

TLDR:使用与整数/数字相同的联合查找代码,但使用散列映射而不是数组来存储联合查找中每个元素的父元素。这种方法适用于任何可以存储在散列映射中的数据类型,而不仅仅是字符串,也就是说,在下面的代码中,两个无序映射可以使用字符串或整数以外的其他数据类型作为键。

代码语言:javascript
复制
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; 
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59841921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档