Java solution, using Arrays.sort(), easy to understand


  • 0
    L
    public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null) return null;
        int size = strs.length;
        if(size == 0) return "";
        
        int temp = strs[0].length();
        
        // find the shortest string in the array, and its size. save it in the "temp" 
        for(int i=0; i<size; i++){
            if(strs[i].length()<temp){
               temp = strs[i].length(); 
            } 
        }
        
        // sort the String array alphabetically
        Arrays.sort(strs);
        
        String result = "";
    
    
        for(int j=0; j<temp; j++){
             // compare the first string with the last char by char, 
            if(strs[0].charAt(j) == strs[size-1].charAt(j)){
                // if they are the same, add into result
                result = result + strs[0].charAt(j);
            }
            else
            {
                break;
            }
        }
        
        return result;
        
    }

  • 0
    D

    public class Solution {
    public String longestCommonPrefix(String[] strs) {
    if(strs.length==0) return "";
    int size=strs.length;
    Arrays.sort(strs);
    //sort array
    int temp=Math.min(strs[0].length(),strs[size-1].length());
    //get the minmum length of the first and last string
    String out="";
    for(int j=0;j<temp;j++)
    {
    if(strs[0].charAt(j)==strs[size-1].charAt(j))
    {
    out=out+strs[0].charAt(j);
    }
    else
    {
    break;
    }
    }
    return out;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.