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,971 questions

51,913 answers

573 users

How to find the longest common string prefix in array of strings in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>

int main() {
    std::string arr[] = {"cartography", "carburettor", "carbonating"}; 
    int size = sizeof(arr)/sizeof(*arr);

    std::sort(arr, arr + size);
    std::cout << arr[0] << " " << arr[1] << " " << arr[2] << "\n";
    
    int length = arr[0].size();
    std::string common_prefix = "";

    for (int i = 0; i < length; i++){
      std::cout << arr[0][i] << " " << arr[size - 1][i] << "\n";      
      std::cout << arr[0] << " " << arr[size - 1] << "\n";
      if (arr[0][i] == arr[size - 1][I]) {
        common_prefix += arr[0][i];
      }
      else {
        break;
      }
    }
    std::cout << "Longest common prefix: " << common_prefix;

    return 0;
}



/*
run:

carbonating carburettor cartography
c c
carbonating cartography
a a
carbonating cartography
r r
carbonating cartography
b t
carbonating cartography
Longest common prefix: car

*/

 



answered Mar 3, 2021 by avibootz
edited Aug 27, 2023 by avibootz
0 votes
#include <iostream>
#include <algorithm>

std::string longestCommonPrefix(std::string arr[], int size) { 
    if (size == 0) 
        return ""; 
  
    if (size == 1) 
        return arr[0]; 

    sort(arr, arr + size); 

    int min_length = std::min(arr[0].size(), arr[size - 1].size()); 
    std::string first = arr[0], last = arr[size - 1]; 
    int i = 0; 
    while (i < min_length && first[i] == last[i]) 
        i++; 
  
    return first.substr(0, i); 
} 

int main() {
    std::string arr[] = {"cartography", "carburettor", "carbonating"}; 

    std::cout << "Longest common prefix: " << longestCommonPrefix(arr, sizeof(arr)/sizeof(*arr));

    return 0;
}



/*
run:

Longest common prefix: car

*/

 



answered Mar 3, 2021 by avibootz
...