Java O(n) easy to understand ,1ms solution


  • 0

    Only one for loop is used so the Time is O(n).

        public String longestCommonPrefix(String[] strs) {
            int x=0;
    /*If length is 0  retrun "" */
            if(strs.length == 0){
                return "";
            }
    /*If length is 1  retrun data */
            if(strs.length <= 1){
                return strs[0];
            }
    /*goes through the while loop and obtains value of x */
            while((strs[0].substring(0,x).equals(strs[1].substring(0,x))) && x<strs[0].length() && x<strs[1].length()){
                x++;
            }
    /* if it is not equal subtracts one */
            if(!(strs[0].substring(0,x).equals(strs[1].substring(0,x))) ){
                x--;
            }
    /* checks the rest of the strings in the array and reduces if length is less or  if content is not equal*/
            for(int i=2;i<strs.length;i++){
                if(x>Math.min(strs[i-1].length(),strs[i].length())){
                     x=Math.min(strs[i-2].length(),strs[i].length());
                }
                 while(!(strs[i-1].substring(0,x).equals(strs[i].substring(0,x)))){
                    x--;
                }
            }
            return strs[0].substring(0,x);
            
        }
    }```

Log in to reply
 

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