Simple solution in java using StringBuffer


  • 0
    Y
    public String longestCommonPrefix(String[] strs) {
        if(strs.length<1) return "";
        StringBuffer prefix = new StringBuffer();
        prefix.append(strs[0]);
        for(int j=1;j<strs.length;j++){
            prefix.delete(lengthOfPrefix(prefix.toString(),strs[j]),prefix.length());
        }
        return prefix.toString();
    }
    public int lengthOfPrefix(String a,String b){
        int min = Math.min(a.length(),b.length());
        int length=0;
        for(int i=0;i<min;i++){
            if(a.charAt(i)==b.charAt(i))
                length++;
            else
                break;
        }
        return length;
    }

  • 0
    B

    Avoid using StringBuffer in single threaded applications. Use StringBuilder which does the same thing faster. StringBuffer is synchronized whereas StringBuilder is not, therefore, StringBuffer will be slower.


Log in to reply
 

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