Anagrammi del gruppo Leetcode

Nov 23 2020

Link qui

Includerò una soluzione in Python e C ++ e potrai esaminarne una. Sono principalmente interessato a rivedere il codice C ++ che è una cosa che ho iniziato a imparare di recente; chi non conosce il C ++ può rivedere il codice Python. Entrambe le soluzioni condividono una logica simile, quindi la revisione si applicherà a qualsiasi.


Dichiarazione problema

Dato un array di stringhe string, raggruppa insieme gli anagrammi. Puoi restituire la risposta in qualsiasi ordine. Un anagramma è una parola o una frase formata riorganizzando le lettere di una parola o frase diversa, in genere utilizzando tutte le lettere originali esattamente una volta.

Esempio:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Entrambe le soluzioni comportano la creazione di una mappatura dai caratteri delle parole ordinati alfabeticamente alla parola corrispondente e ogni parola incontrata che è una corrispondenza, viene aggiunta al gruppo corrispondente. E poiché è stato suggerito in precedenza nei miei post precedenti di non fare affidamento sulle statistiche di leetcode perché sono imprecise, ho cronometrato entrambe le soluzioni c ++ e python per 1.000.000 di esecuzioni sullo stesso set di parole per vedere cosa viene fuori. Sorprendentemente, la soluzione python supera la soluzione c ++ quasi di 2x. I tempi risultanti ~ = 10, 20 secondi per python e c ++ rispettivamente quando vengono eseguiti sul mio i5 2.7 GHZ mbp. Dato che entrambe le implementazioni sono quasi simili, C ++ non dovrebbe essere 10 volte più veloce di Python?

group_anagrams.py

from collections import defaultdict
from time import perf_counter


def group(words):
    groups = defaultdict(lambda: [])
    for word in words:
        groups[tuple(sorted(word))].append(word)
    return groups.values()


def time_grouping(n, words):
    print(f'Calculating time for {n} runs ...')
    t1 = perf_counter()
    for _ in range(n):
        group(words)
    print(f'Time: {perf_counter() - t1} seconds')


if __name__ == '__main__':
    w = [
        'abets',
        'baste',
        'beats',
        'tabu',
        'actress',
        'casters',
        'allergy',
        'gallery',
        'largely',
    ]
    print(list(group(w)))
    time_grouping(1000000, w)

Risultati:

[['abets', 'baste', 'beats'], ['tabu'], ['actress', 'casters'], ['allergy', 'gallery', 'largely']]
Calculating time for 1000000 runs ...
Time: 8.801584898000002 seconds

group_anagrams.h

#ifndef LEETCODE_GROUP_ANAGRAMS_H
#define LEETCODE_GROUP_ANAGRAMS_H

#include <vector>
#include <string>

std::vector<std::vector<std::string>> get_groups(const std::vector<std::string> &words);

#endif //LEETCODE_GROUP_ANAGRAMS_H

group_anagrams.cpp

#include "group_anagrams.h"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <map>


std::vector<std::vector<std::string>>
get_groups(const std::vector<std::string> &words) {
    std::map<std::string, std::vector<std::string>> word_groups;
    std::vector<std::vector<std::string>> groups;
    for (const auto &word: words) {
        auto sorted_word = word;
        std::sort(sorted_word.begin(), sorted_word.end());
        if (word_groups.contains(sorted_word)) {
            word_groups[sorted_word].push_back(word);
        } else {
            word_groups[sorted_word] = {word};
        }
    }
    groups.reserve(word_groups.size());
    for (auto const &imap: word_groups)
        groups.push_back(imap.second);
    return groups;
}


int main() {
    std::vector<std::string> words{
            "abets", "baste", "beats", "tabu", "actress", "casters", "allergy",
            "gallery", "largely"
    };
    auto groups = get_groups(words);
    for (const auto &group: groups) {
        for (const auto &word: group)
            std::cout << word << ' ';
        std::cout << '\n';
    }
    size_t n_times{1000000};
    std::cout << "\nCalculating time for " << n_times << " runs ..." << '\n';
    auto t1 = std::chrono::high_resolution_clock::now();
    while (n_times > 0) {
        get_groups(words);
        n_times--;
    }
    auto t2 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::seconds>(
            t2 - t1).count();
    std::cout << duration << " seconds";
}

Risultati:

abets baste beats 
tabu 
actress casters 
allergy gallery largely 

Calculating time for 1000000 runs ...
22 seconds

Risposte

1 user673679 Nov 23 2020 at 09:20

C ++

    if (word_groups.contains(sorted_word)) {
        word_groups[sorted_word].push_back(word);
    } else {
        word_groups[sorted_word] = {word};
    }

containscerca la parola in word_groups. Quindi operator[]esegue la stessa ricerca una seconda volta.

Possiamo sostituire quanto sopra con solo:

    word_groups[sorted_word].push_back(word);

( operator[]inserisce un valore costruito di default (cioè un vuoto vector<std::string>) se non è presente nella mappa).


Non è necessario copiare la word_groupsmappa in un vettore per restituirla get_groups(). Possiamo semplicemente restituire la mappa stessa.

Quindi nella funzione principale lo itereremmo con:

for (const auto &group: groups) { // group is a pair (.first is the key, .second is the values)
    for (const auto &word: group.second)
        ...

Non abbiamo bisogno di memorizzare la stringa stessa nella mappa, possiamo memorizzare l'indice della stringa nel vettore di input. (cioè map<string, vector<std::size_t>>).