14. Longest Common Prefix

class Solution {

    /**
     * @param String[] $strs
     * @return String
     */
    function longestCommonPrefix($strs) {
        if (count($strs) === 1 && $strs[0] === ''){
            return '';
        }
        $commonPrefix = '';
        $total = count($strs);
        $targets = array_map(fn($str)=> str_split($str), $strs);
        $lastKey = array_key_last($strs);
        $startWord = $targets[0][0] ?? '';
        $startKey = 0;
        while(true) {
            foreach($targets as $target){
                if (!isset($target[$startKey]) || $target[$startKey] !== $startWord){
                    return $commonPrefix;
                }
            }
            $commonPrefix .= $startWord;
            ++$startKey;
            $startWord = $targets[0][$startKey];
        }
    }
}

Last updated