clueless coding // TODO: be smarter

LeetCode Longest Common Prefix: Java Solution



TL;DR Code Solution


public String longestCommonPrefix(String[] strs) {

    StringBuilder res = new StringBuilder();

    if (strs.length == 0) {
        return res.toString();
    }

    for (int i = 0; i < strs[0].length(); i++) {
        char cur = strs[0].charAt(i);
        for (int j = 0; j < strs.length; j++) {
            if (i >= strs[j].length() || strs[j].charAt(i) != cur) {
                 return res.toString();
            }
        }
        res.append(cur);
    }

    return res.toString();


}