Longest Common Prefix in Java



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:
No. 1 JAVA Version


Alternative Solution:2

string Solution::longestCommonPrefix(vector &A) {
    string result = "";
    auto n = A.size();
    int j = INT_MAX;
    for (auto i = 0; i
    {
        auto s = A[i].length();
        if (j > s)
            j = s;
    }
    
    for (auto i = 0; i
    {
        auto temp = A[0][i];
        int k = 1;
        while (k
        {
            if (temp==A[k][i])
                ++k;
            else
                return result;
        }
        result += temp; 
    }
    return result;
}



No comments