SImple Iterative 13 lines Java Solution


  • 0
    Z
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0)  return "";
        StringBuilder sb = new StringBuilder();
        for(int cur = 0; cur < strs[0].length(); cur++){
            char c = strs[0].charAt(cur);
            for(int i = 1; i < strs.length; i++)
                if(strs[i].length() - 1 < cur || strs[i].charAt(cur) != c) return sb.toString();
            sb.append(c);
        }
        return sb.toString();
    }

Log in to reply
 

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