原文:

给定一个小写的单词列表。实现一个函数来查找所有具有相同唯一字符集的单词。

示例:

input: words[] = { "may", "student", "students", "dog",
                 "studentssess", "god", "cat", "act",
                 "tab", "bat", "flow", "wolf", "lambs",
                 "amy", "yam", "balms", "looped", 
                 "poodle"};
output : 
looped, poodle, 
lambs, balms, 
flow, wolf, 
tab, bat, 
may, amy, yam, 
student, students, studentssess, 
dog, god, 
cat, act, 
all words with same set of characters are printed 
together in a line.

想法是使用散列法。我们为所有单词生成一个密钥。密钥包含所有唯一字符(小写字母的密钥大小最多为 26)。我们将单词索引存储为键值。一旦我们填充了哈希表中的所有键和值,我们就可以通过遍历该表来打印结果。

以下是上述想法的实现。

c

// c   program to print all words that have
// the same unique character set
#include
using namespace std;
#define max_char 26
// generates a key from given string. the key
// contains all unique characters of given string in
// sorted order consisting of only distinct elements.
string getkey(string &str)
{
    bool visited[max_char] = { false };
    // store all unique characters of current
    // word in key
    for (int j = 0; j < str.length(); j  )
        visited[str[j] - 'a'] = true ;
    string key = "";
    for (int j=0; j < max_char; j  )
        if (visited[j])
            key = key   (char)('a' j);
    return key;
}
// print all words together with same character sets.
void wordswithsamecharset(string words[], int n)
{
    // stores indexes of all words that have same
    // set of unique characters.
    unordered_map  > hash;
    // traverse all words
    for (int i=0; i

java 语言(一种计算机语言,尤用于创建网站)

// java program to print all words that have
// the same unique character set
import java.util.arraylist;
import java.util.arrays;
import java.util.hashmap;
import java.util.map.entry;
public class gfg {
    static final int max_char = 26;
    // generates a key from given string. the key
    // contains all unique characters of given string
    // in sorted order consisting of only distinct elements.
    static string getkey(string str)
    {
        boolean[] visited = new boolean[max_char];
        arrays.fill(visited, false);
        // store all unique characters of current
        // word in key
        for (int j = 0; j < str.length(); j  )
            visited[str.charat(j) - 'a'] = true ;
        string key = "";
        for (int j=0; j < max_char; j  )
            if (visited[j])
                key = key   (char)('a' j);
        return key;
    }
    // print all words together with same character sets.
    static void wordswithsamecharset(string words[], int n)
    {
        // stores indexes of all words that have same
        // set of unique characters.
        //unordered_map  > hash;
        hashmap> hash = new hashmap<>();
        // traverse all words
        for (int i=0; i get_al = hash.get(key);
                get_al.add(i);
                hash.put(key, get_al);
            }
            // if key is not present in the map
            // then create a new list and add
            // both key and the list
            else
            {
                arraylist new_al = new arraylist<>();
                new_al.add(i);
                hash.put(key, new_al);
            }
        }
        // print all words that have the same unique character set
        for (entry> it : hash.entryset())
        {
            arraylist get =it.getvalue();
            for (integer v:get)
                system.out.print( words[v]   ", ");
            system.out.println();
        }
    }
    // driver program to test above function
    public static void main(string args[])
    {
        string words[] = { "may", "student", "students", "dog",
                     "studentssess", "god", "cat", "act", "tab",
                     "bat", "flow", "wolf", "lambs", "amy", "yam",
                     "balms", "looped", "poodle"};
        int n = words.length;
        wordswithsamecharset(words, n);
    }
}
// this code is contributed by sumit ghosh

计算机编程语言

# python program to print all words that
# have the same unique character set
# function to group all strings with same characters
from collections import counter
def groupstrings(input):
    # traverse all strings one by one
    # dict is an empty dictionary
    dict={}
    for word in input:
        # sort the current string and take it's
        # sorted value as key
        # sorted return list of sorted characters
        # we need to join them to get key as string
        # counter() method returns dictionary with frequency of
        # each character as value
        worddict=counter(word)
        # now get list of keys
        key = worddict.keys()
        # now sort these keys
        key = sorted(key)
        # join these characters to produce key string
        key = ''.join(key)
        # now check if this key already exist in
        # dictionary or not
        # if exist then simply append current word
        # in mapped list on key
        # otherwise first assign empty list to key and
        # then append current word in it
        if key in dict.keys():
            dict[key].append(word)
        else:
            dict[key]=[]
            dict[key].append(word)
        # now traverse complete dictionary and print
        # list of mapped strings in each key separated by ,
    for (key,value) in dict.iteritems():
        print ','.join(dict[key])
# driver program
if __name__ == "__main__":
    input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','wolf','lambs','amy','yam','balms','looped','poodle']
    groupstrings(input)

c

// c# program to print all words that
// have the same unique character set
using system;
using system.collections.generic;
class gfg{
static readonly int max_char = 26;
// generates a key from given string. the
// key contains all unique characters of
// given string in sorted order consisting
// of only distinct elements.
static string getkey(string str)
{
    bool[] visited = new bool[max_char];
    // store all unique characters of current
    // word in key
    for(int j = 0; j < str.length; j  )
        visited[str[j] - 'a'] = true;
    string key = "";
    for(int j = 0; j < max_char; j  )
        if (visited[j])
            key = key   (char)('a'   j);
    return key;
}
// print all words together with same character sets.
static void wordswithsamecharset(string []words, int n)
{
    // stores indexes of all words that have same
    // set of unique characters.
    //unordered_map  > hash;
    dictionary> hash = new dictionary>();
    // traverse all words
    for (int i = 0; i < n; i  )
    {
        string key = getkey(words[i]);
        // if the key is already in the map
        // then get its corresponding value
        // and update the list and put it
        // in the map
        if (hash.containskey(key))
        {
            list get_al = hash[key];
            get_al.add(i);
            hash[key]= get_al;
        }
        // if key is not present in the map
        // then create a new list and add
        // both key and the list
        else
        {
            list new_al = new list();
            new_al.add(i);
            hash.add(key, new_al);
        }
    }
    // print all words that have the
    // same unique character set
    foreach(keyvaluepair> it in hash)
    {
        list get =it.value;
        foreach(int v in get)
            console.write( words[v]   ", ");
        console.writeline();
    }
}
// driver code
public static void main(string []args)
{
    string []words = { "may", "student", "students",
                       "dog", "studentssess", "god",
                       "cat", "act", "tab",
                       "bat", "flow", "wolf",
                       "lambs", "amy", "yam",
                       "balms", "looped", "poodle"};
    int n = words.length;
    wordswithsamecharset(words, n);
}
}
// this code is contributed by princi singh

输出:

looped, poodle, 
lambs, balms, 
flow, wolf, 
tab, bat, 
may, amy, yam, 
student, students, studentssess, 
dog, god, 
cat, act, 

时间复杂度: o(n*k)其中 n 是字典中的字数,k 是一个单词的最大长度。

本文由 供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 contribute@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如果发现有不正确的地方,或者想分享更多关于上述话题的信息,请写评论。