Java solution using StringBuilder


  • 0
    A
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0) return "";
        StringBuilder cp = new StringBuilder();
        String str = strs[0];
        for(int i = 0; i < str.length(); i++){
            char a = str.charAt(i);
            for(String tmp : strs) {
                if(tmp.length() < i + 1 || tmp.charAt(i) != a)
                    return cp.toString();
            }
            cp.insert(i, a);   //here you can also use append(a);
        }
        return cp.toString();
    }

Log in to reply
 

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