Java 12ms solution without inBuilt Functions


  • 0
    S
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs.length == 0 || strs == null)
                return "";
            if(strs.length == 1)
                return strs[0];
            char[] prefix = strs[0].toCharArray();
            int prefixLength = prefix.length;
            StringBuilder res = new StringBuilder();
            int len = strs.length;
            
            for(int i=0;i<prefixLength;i++){
                for(int arrIndex=1; arrIndex < len ; arrIndex++){
                    if(i >= strs[arrIndex].length() || strs[arrIndex].charAt(i)!=prefix[i]){
                            return res.toString();
                    }
                }
                res.append(prefix[i]);
            }
            return res.toString();
        }
    }
    

Log in to reply
 

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