Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,972 questions

51,915 answers

573 users

How to find the longest common prefix in a vector of strings in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

std::string prefix(std::string result, std::string vecstr) {
    std::string prefixstr;
    int sizer = result.length();
    int sizevstr = vecstr.length();
    
    for (int i = 0, j = 0; (i <= sizer - 1) && (j <= sizevstr - 1); i++, j++) {
        if (result[i] != vecstr[j]) {
            break;
        }
        prefixstr.push_back(result[i]); 
    }
    return prefixstr;
}
std::string common_prefix(std::vector<std::string> vec) {
    std::string result = vec[0];
    for (int i = 1; i <= vec.size() - 1; i++) {
        result = prefix(result, vec[i]);
    }
    return result;
}
 
int main()
{
    std::vector<std::string> vec = {"cartography", "carburettor", "carbonating", "cardholder", "caramelize"};
    
    std::string result = common_prefix(vec);
    
    std::cout << result;
}



/*
run:
  
car
  
*/

 



answered Aug 27, 2023 by avibootz
...