My Solution using ArrayList and StringBuilder


  • 0
    M
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        List<String> list = new ArrayList<>();
        list.add(strs[0]);
        for (int i = 1; i < strs.length; i++) {
            if (list.get(0).length() > strs[i].length()) {
                list.remove(0);
                list.add(strs[i]);
            }
        }
        StringBuilder answer = new StringBuilder();
        String temp = list.get(0);
        for (int i = 0; i < temp.length(); i++) {
            for (int j = 0; j < strs.length; j++) {
                if (temp.charAt(i) != strs[j].charAt(i)) return answer.toString();
            }
            answer.append(temp.charAt(i));
        }
        return answer.toString();
    }

Log in to reply
 

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