My Java solution. 309 ms


  • 3
    Y
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs.length == 0)
                return "";
            if (strs.length == 1)
                return strs[0];
            String prefix = "", minSt = strs[0];
            for (String st: strs)
                if (st.length() < minSt.length()) 
                    minSt = st;
            for (int i=0; i<minSt.length(); i++) {
                for (String st: strs)
                    if (st.charAt(i) != minSt.charAt(i))
                        return prefix;
                prefix += minSt.charAt(i);
            }
            return prefix;
        }
    }

Log in to reply
 

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