LeetCode Longest Common Prefix Java

WaiChun
Mar 7, 2021

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: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

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

Constraints:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.
class Solution {
public String longestCommonPrefix(String[] strs) {

if(strs.length ==0){
return "";
}

int length = strs[0].length();
String result = "";

for(int i =0; i<strs.length; i++){
if(length > strs[i].length()){
length = strs[i].length();
}
}

for(int i = length ; i> 0 ; i--){
result = strs[0].substring(0, i);
for(int j=0; j<strs.length;j++){
if(!result.equals(strs[j].substring(0,i))){
result = "";
break;
}
}
if(result.length() != 0){
return result;
}
}
return result;
}
}

--

--