最长公共前缀

class Solution
{

    /**
     * @param  String[]  $strs
     * @return String
     */
    function longestCommonPrefix(array $strs): string
    {
        $count = count($strs);
        if ($count === 0) {
            return "";
        }

        if ($count === ·) {
            return $strs[0];
        }

        $minLen = strlen($strs[0]);

        foreach ($strs as $str) {
            $minLen = min($minLen, strlen($str));
        }

        $maxSameLenContinuously = 0;
        for ($i = 0; $i < $minLen; $i++) {
            $char = null;
            $isSame = true;
            for ($j = 0; $j < $count; $j++) {
                if ($j === 0) {
                    $char = $strs[0][$i];
                } elseif ($strs[$j][$i] !== $char) {
                    $isSame = false;
                }
            }
            if ($isSame) {
                $maxSameLenContinuously++;
            } else {
                break;
            }
        }

        return substr($strs[0], 0, $maxSameLenContinuously);
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
无论在现实或是网络中,我都是孤独的。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!