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,
- Leetcode Longest Common Prefix problem solution in C++
- Leetcode Longest Common Prefix problem solution in C
- Leetcode Longest Common Prefix problem solution in Python
- Leetcode Longest Common Prefix problem solution in C#