C++ Exercises: Find the longest common prefix from a given array of strings
C++ String: Exercise-16 with Solution
Write a C++ program to find the longest common prefix from a given array of strings.
Example-1:
Input: Array of strings
String | Positions | |||||
---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | |
String-1 | P | a | d | a | s | |
String-2 | P | a | c | k | e | d |
String-3 | P | a | c | e | ||
String-4 | P | a | c | h | a |
Output: Pa
Example-2:
Input: Array of strings
String | Positions | |||||
---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | |
String-1 | J | a | c | k | e | t |
String-2 | J | o | i | n | t | |
String-3 | J | u | n | k | y | |
String-4 | J | e | t |
Output: J
Example-3:
Input: Array of strings
String | Positions | |||||
---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | |
String-1 | B | o | r | t | ||
String-2 | W | h | a | n | g | |
String-3 | Y | a | r | d | e | r |
String-4 | Z | o | o | n | i | c |
Output:
Sample Solution:
C++ Code:
#include <iostream>
#include<algorithm>
using namespace std;
string longest_Common_Prefix(string arr_strings[], int arr_size)
{
// If array size is 0, return empty string
int size = arr_size;
string str = arr_strings[0];
if(size == 1)
return str;
string result = "";
int j = 1;
for(int i=0; i<size; i++){
while(j < size){
if(str[i] == arr_strings[j][i]){
j++;
}
else{
return result;
}
}
result += str[i];
j = 1;
}
return result;
}
int main()
{
string arr_strings[] = {"Padas", "Packed", "Pace", "Pacha"};
int arr_size = sizeof(arr_strings) / sizeof(arr_strings[0]);
cout << "The longest common prefix is: "
<< longest_Common_Prefix(arr_strings, arr_size);
string arr_strings1[] = {"Jacket", "Joint", "Junky", "Jet"};
arr_size = sizeof(arr_strings) / sizeof(arr_strings1[0]);
cout << "\nThe longest common prefix is: "
<< longest_Common_Prefix(arr_strings1, arr_size);
string arr_strings2[] = {"Bort", "Whang", "Yarder", "Zoonic"};
arr_size = sizeof(arr_strings) / sizeof(arr_strings1[0]);
cout << "\nThe longest common prefix is: "
<< longest_Common_Prefix(arr_strings2, arr_size);
return 0;
}
Sample Output:
The longest common prefix is: Pa The longest common prefix is: J The longest common prefix is:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to convert a given non-negative integer to English words.
Next: Write a C++ program to find all combinations of well-formed brackets from a given paris of parentheses.What is the difficulty level of this exercise?