Java Code without using inbuilt String methods.


  • 0
    B

    Let me know if anyone finds more optimized solution.

      public String longestCommonPrefix(String[] strs) {
        String prefix = "";
        int len = strs.length;
        if (strs != null && len > 0) {
            prefix = strs[0];
            for (int i = 1; i < len; i++) {
                if (prefix == "") {
                    break;
                }
                prefix = extractCommonString(prefix, strs[i]);
            }
        }
        return prefix;
    }
    
     private String extractCommonString(String str1, String str2) {
        StringBuilder builder = new StringBuilder();
        int min = Math.min(str1.length(), str2.length());
        int i = 0;
        while (i < min && str1.charAt(i) == str2.charAt(i)) {
            builder.append(str1.charAt(i));
            i++;
        }
        return builder.toString();
    }
    

Log in to reply
 

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