Longest common prefix in C++



LongestCommonPrefix
Given the array of strings as input1, write a program to find the longest S which is the prefix of ALL the strings in the array. As an example, longest common prefix of "abcdefgh" and "abcefgh" is "abc".
Business Rules
There is no prefix found print "No longest common prefix found".
Input Format
First input is a integer value,Second and Third input values are string respectively.
Refer sample input for the format.
Output Format
Output contains the longest common prefix. Refer sample output for the format.
Sample Input 1
2
Sky is blue
Sky is dark
Sample Output 1
Sky is 

Sample Input 2:
 

abc
def
ghi
Sample Output 2:  
No longest common prefix found 

Function specification is the following for C#, Java and C++.
Name:-LongestCommonPrefix (C#)/longestCommonPrefix (Java,C++)
Return Type:- string
Parameter(s):- string[] input1
Function specification for C is the following.
Name:-longestCommonPrefix  
Return Type:- char*
Parameter(s):- char** input1,int size;

Solution:

Image result for c++


In C++ Solution:


#include"iostream"   /*use <; instead of "/
#include"string.h"
using namespace std;
int main()
{
    char a[100][100],y[100];
    int i,j,n,x=0,flag=0,count=0;
    cin>>n;
    cin.getline(y,100);
    for(j=0;j
    {
        cin.getline(a[j],100);
        if(x
            x=strlen(a[j]);
    }
    for(i=0;i
    {
        flag=1;
        for(j=0;j
        {  
            if(a[j][i]==a[j+1][i])
            {

            }
            else
            {
                flag=0;
                if(count==0)
                {
                    cout<<"No longest common prefix found";
                }
                return 0;
            }
        }
        if(flag==1)
        {
            count=1;
            cout<
        }


    }
    return 0;
}



No comments