My Java solution


  • 0
    C
    public class Solution {
    public String longestCommonPrefix(String[] strs) {
        //
        if(strs == null || strs.length == 0)
            return "";
        if(strs.length == 1)
            return strs[0];
        
        for(int i=0;i<strs.length;i++)
        {
            if(strs[i] == null || strs[i].length() == 0)
                return "";
        }
        
        StringBuffer sb = new StringBuffer();
        
        for(int i=0;i<strs[0].length();i++)
        {
            //get the i-th element from the first String
            char current = strs[0].charAt(i);
            for(int j=1;j<strs.length;j++)
            {
                if(strs[j].length() <=i ||strs[j].charAt(i) != current)
                    return sb.toString();
            }
            sb.append(current);
        }
        return sb.toString();
    }
    

    }


Log in to reply
 

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