1ms simple clean java solution o(n2)


  • 0
    H

    strs[i].indexOf(prefix) will return 0 if "prefix" is a prefix of strs[i]

    otherwise, remove the last letter from the end, until no common prefix(length == 0)

    public String longestCommonPrefix(String[] strs) {
        if(null == strs || strs.length == 0)  return "";
        String prefix = strs[0];
        for(int i =1;i<strs.length;i++){
            while(strs[i].indexOf(prefix)!=0){
                prefix = prefix.substring(0, prefix.length()-1);
            }
        }
        return prefix;
    }

  • 0
    This post is deleted!

  • 0
    H

    That make sense. Thanks.


Log in to reply
 

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