131. 分割回文串

链接 (opens new window) 20240221164903_image.png

20240221164916_image.png 20240221165007_image.png

class Solution {

    public $result = [];

    /**
     * @param String $s
     * @return String[][]
     */
    function partition($s) {
        $len = strlen($s);
        $this->dfs($s, 0, $len, []);
        return $this->result;
    }

    function dfs($s, $start, $len, $path) {
        if($start == $len) {
            $this->result[] = $path;
            return;
        }
        for ($i = $start; $i < $len; $i++) {
            if (!$this->isPalindrome($s, $start, $i)) {
                continue;
            }
            $path[] = substr($s, $start, $i + 1 - $start);
            $this->dfs($s, $i + 1, $len, $path);
            array_pop($path);
        }
    }

    /**
     * 判断字符串中指定范围是否是回文串
     * @param $s
     * @param $left
     * @param $right
     * @return bool
     */
    function isPalindrome($s, $left, $right) {
        while ($left < $right) {
            if ($s[$left] != $s[$right]) {
                return false;
            }
            $left++;
            $right--;
        }
        return true;
    }
}

copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48