Longest Common Prefix No 14

Java Solution

Posted by Captain Nimo 1 month ago

Question

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

Code

public String longestCommonPrefix(String[] strs){
  if(strs==null||strs.length==0) return "";
  String prefix =strs[0];
  for(int i=1;i<strs.length;i++){
    int j=0;
    while(j<strs[i].length()&&j<prefix.length()&&strs[i].charAt(j)==prefix.charAt(j)){
      j++
    }
    prefix=prefix.substring(0,j);
  }
  return prefix;
}