fork download
  1. // A C++ Program to find the longest
  2. // common prefix
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // A Utility Function to find the common
  7. // prefix between strings- str1 and str2
  8. string commonPrefixUtil(string str1,
  9. string str2)
  10. {
  11. string result;
  12. int n1 = str1.length(),
  13. n2 = str2.length();
  14.  
  15. // Compare str1 and str2
  16. for (int i = 0, j = 0; i <= n1 - 1 &&
  17. j <= n2 - 1; i++, j++)
  18. {
  19. if (str1[i] != str2[j])
  20. break;
  21. result.push_back(str1[i]);
  22. }
  23.  
  24. return (result);
  25. }
  26.  
  27. // A Function that returns the longest
  28. // common prefix from the array of strings
  29. string commonPrefix (string arr[], int n)
  30. {
  31. string prefix = arr[0];
  32.  
  33. for (int i = 1; i <= n - 1; i++)
  34. prefix = commonPrefixUtil(prefix,
  35. arr[i]);
  36. return (prefix);
  37. }
  38.  
  39. // Driver code
  40. int main()
  41. {
  42. string arr[] = {"geeksforgeeks", "eeks",
  43. "eek", "eekzer"};
  44. int n = sizeof(arr) / sizeof(arr[0]);
  45. string ans = commonPrefix(arr, n);
  46.  
  47. if (ans.length())
  48. printf ("The longest common prefix is - %s",
  49. ans.c_str());
  50. else
  51. printf("There is no common prefix");
  52.  
  53. return (0);
  54. }
  55.  
Success #stdin #stdout 0.01s 5460KB
stdin
Standard input is empty
stdout
There is no common prefix