dsfafaadfsa

leetcode每日一题之8.分割回文串

分割回文串

回溯算法

求所有解,所以使用回溯算法来枚举所有的解。代码如下

class Solution {

    /**
     * @param String $s
     * @return String[][]
     */
    function partition($s) {
        $res = [];
        $this->backtrack($s, $res, []);
        return $res;
    }

    /**
     * 回溯函数 
     */
    function backtrack($string, &$res, $path){
        // 当传过来的字符串为空,说明之前的所有字串都为回文串
        if(strlen($string) == 0){
            array_push($res, $path);
            return $res;
        }

        for($i= 1; $i <= strlen($string); ++$i){
            $pre = substr($string, 0, $i);
            if($this->isPalindrome($pre)){
                array_push($path, $pre);
                $this->backtrack(substr($string, $i), $res, $path);
                array_pop($path);
            }
        }
    }

    /**
     * 判断是不是回文串
     */
    function isPalindrome($string){
        $left = 0;
        $right = strlen($string) - 1;
        while($left < $right){
            if($string[$left] != $string[$right]){
                return false;
            }
            $left++;
            $right--;
        }
        return true;
    }
}


动态规划预处理

每次判断是否是回文的时候,会重复判断,例如abba.所以使用动态规划,将所有的回文子串查出来。代码如下:

class Solution {

    public $palindromeArray;
    /**
     * @param String $s
     * @return String[][]
     */
    function partition($s) {
        $res = [];
        $this->palindrome($s);
        $this->backtrack($s, $res, [], 0);
        return $res;
    }

    /**
     * 回溯函数 
     */
    function backtrack($string, &$res, $path, $left){
        // 当传过来的字符串为空,说明之前的所有字串都为回文串
        if(strlen($string) == 0){
            array_push($res, $path);
            return $res;
        }

        // 循环回溯子串
        for($i= 1; $i <= strlen($string); ++$i){
            $pre = substr($string, 0, $i);
            if($this->palindromeArray[$left][$left + $i - 1]){
                array_push($path, $pre);
                $this->backtrack(substr($string, $i), $res, $path, $left + $i);
                array_pop($path);
            }
        }
    }

    /**
     * 动态规划查出所有的回文字符串
     */
    function palindrome($string){
        for($right = 0; $right < strlen($string); ++$right){
            for($left = $right; $left >= 0; --$left){
                if($string[$left] == $string[$right] && ($right - $left < 2 || $this->palindromeArray[$left + 1][$right - 1])){
                    $this->palindromeArray[$left][$right] = true;
                } else {
                    $this->palindromeArray[$left][$right] = false;
                }
            }
        }
    }
}

posted @   狩猎者丿七夜  阅读(41)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示