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;
                }
            }
        }
    }
}

原文地址:https://www.cnblogs.com/qiye5757/p/14495743.html