14. Longest Common Prefix

time: O(s), all the chars

space: O(1)

class Solution {
    public String longestCommonPrefix(String[] strs) {
        // [abc, cds, ab] => ""
        // [abc, ab, a] => "a"
        // [aaa, bbb, cc] = > ""
        // fiist is to compare each char in string array one by one, it will be n^2
        
        // another one is base on first String, compare others and narrow the String range,
        if (strs == null || strs.length == 0) return "";
        
        String pre = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (!strs[i].startsWith(pre)) {
                pre = pre.substring(0, pre.length() - 1);
            }
        }
        return pre;
     }
}

like binary search idea, separate to two parts

time: O(slogn), s: all the chars

space: O(1)

Last updated

Was this helpful?