Search code examples
javaarraysstringcharacterprefix

Longest Common Prefix in String Array in Java


I am trying to find a longest common prefix in a string array using java. Following is my solution but when i upload it on leetcode, it fails and i don't understand which test case does it fail. All the test cases that I have tested works fine.

My approach is to match the first character of all the words in string array and if all words have similar first character then it move to the second character otherwise the function returns the string.

If someone helps me identify the test case where my code fails, i will be really grateful. Following is the code i have written:

public static String LongCommonPrefix(String[] strs)
    {
        String commonPrefix="";
        int count=0, k=0;
        
        if(strs.length>0)
        {
            for(int i=0; i<strs[0].length(); i++)
            {
                int j=1;
                while(j<strs.length)
                {
                    if(strs[0].charAt(k)==strs[j].charAt(k))
                    {
                        count++;
                        j++;
                    }
                    else
                        break;
                }
                if(count==strs.length-1)
                {
                    commonPrefix+=strs[0].charAt(k);
                    count=0;
                    k++;

                }
                else
                {
                    return commonPrefix;
                }

            }
        }

        return commonPrefix;
    }

Solution

  • The error in your code is in the part you used without checking that the variable (K) might be larger than the string length (j) of the array. To solve this problem, it is enough to add a conditional statement before using the variable (K). Good luck