Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

compare multiple string array's to find simular chars



  • hello,

    the example input string array's are:

    abcdde
    baccd
    eeabg
    

    'a' and 'b', occur in the example string array's.
    but it could be any number lower case char but it has to occur in all array's.
    the number of strings inside a vector could be 1 to 100 and not necessarily of equal length.

    what kind of mechanism will it take?


  • Moderators

    Well there's not much to invent here. You need to do a loop over all strings, an inner loop over your chars and a find.
    One possible optimization could be to sort each string and the characters first. This way you could start the find for next character where you ended with the previous one. If the strings are long and characters sparse it might be worth using a binary search or creating a set of characters out of each string first. But that's something you'd have to measure on your particular data set because it might not be worth it.
    Another optimization could be multithreading - do each string in a parallel thread.



  • @Chris-Kawa
    this is what i came up with:

    int findSimularchars(vector<string> arr) {
    
        std::map<char, int> values;
    
        char alpha[] = "abcdefghijklmnopqrstuvwxyz";
    
        for (long unsigned int i = 0; i < strlen(alpha); i++)
        {
            values.insert(std::make_pair(alpha[i], 0)); 
        }
    
        for(auto ii : arr){
            for(long unsigned int j = 0; j < strlen(alpha); j++){
                std::size_t found=ii.find(alpha[j]);
                if (found!=std::string::npos){
                    std::map<char, int>::iterator it = values.find(alpha[j]); 
                    if (it != values.end())
                    it->second = it->second + 1;
                }
            }
        }
    
        int counter = 0;
        for(auto& x : values)
        {
            if(x.second == arr.size()){
                counter++;
            }
        }
        return counter;
    }
    

    works perfect.


Log in to reply