Clean Java Solution, Easy to understand


  • 0
    H
    /**
    Constraints
        array size >= 0
        
    Tests
        {} -> ""
        {"abc"} -> "abc"
        {"abc", "edf"} -> ""
        {"abc", "ade", "acg"} -> "a"
        {"abc", "ab"} -> "ab"
    
    Ideas
        pick the first str as pivot and increase k if others share the same char
            time o(n)
            space o(k) where k is size of the longest common prefix
    */
    class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs == null || strs.length == 0) return "";
            if(strs.length == 1) return strs[0];
            String pivot = strs[0];
            int k = 0;
            while(k < pivot.length()) {
                if(!isCommon(strs, k, pivot.charAt(k))) break;  
                k++;
            }
            return pivot.substring(0, k);
        }
        
        private boolean isCommon(String[] strs, int k, char c) {
            for(int i = 1; i < strs.length; i++) {
                String str = strs[i];
                if(str.length() <= k || strs[i].charAt(k) != c) return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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