Longest Common Prefix Java Solution - The Coding Shala

Home >> Interview Questions >> Longest Common Prefix

Longest Common Prefix

Problem:

Write a function to find the longest common prefix string amongst an array of strings.



If there is no common prefix, return an empty string "".


Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

Longest Common Prefix Java Solution

Approach:

We will check character at every index of every string given in array if not matched then will break the loop.

Java Code:: 

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        if(strs == null || len == 0) return "";
        String check = strs[0];
        int index = check.length();
        for(int i=1; i< len; i++){
            for(int j=0; j< index; j++){
                if(j >= strs[i].length() || check.charAt(j) != strs[i].charAt(j)){
                    index = j;
                    break;
                }
            }
        }
        return check.substring(0, index);
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Decimal to Binary - The Coding Shala