Leetcode Longest Common Prefix problem solution in Java programming

In the Leetcode Longest Common Prefix problem solution in Java programming 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 “”.

Leetcode Longest Common Prefix problem solution in Java programming

public class Solution {

public String longestCommonPrefix(String[] strs) {
    int len;
    if((len=strs.length)==0) return "";
    int j=0;
    while(true){
        HashSet<Character> set = new HashSet<Character>();
            if(j<strs[0].length())
                set.add(strs[0].charAt(j));
            else
                return strs[0];
        for(int i=1;i<len;i++){
            if(j==strs[i].length() || set.add(strs[i].charAt(j))){
                return strs[0].substring(0,j);
            }
        }
        j++;
    }
}
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *