Java code using StringBuilder


  • 0
    R
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs.length == 0) return "";
            
            StringBuilder commonPrefix = new StringBuilder(strs[0]);
            for(int i=1; i<strs.length; i++) {
                int end = Math.min(commonPrefix.length(), strs[i].length());
                commonPrefix.delete(end,commonPrefix.length());
                int j;
                for(j=0; j<end; j++) {
                    if(strs[i].charAt(j) != commonPrefix.charAt(j))
                        break;
                }
                commonPrefix.delete(j,commonPrefix.length());
            }
            return commonPrefix.toString();
        }
    }
    

Log in to reply
 

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