【回溯】【回文字符串】131.分割回文串

本文详细阐述了两种DFS方法,分别应用于字符串分割和回文串判断,展示了如何利用ArrayList和动态规划优化性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

法1:DFS+双指针

Python

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res = list()
        tmp = list()
        self.dfs(0, s, tmp, res)
        return res

    def dfs(self, idx, s, tmp, res):
        if idx == len(s):
            res.append(tmp.copy())
        
        for i in range(idx, len(s)):
            if self.is_valid(s, idx, i):
                tmp.append(s[idx:i+1])
                self.dfs(i+1, s, tmp, res)
                tmp.pop()
    
    def is_valid(self, s, i, j) -> bool:
        if i < 0 or i >= len(s) or j < 0 or j >= len(s) or i > j:
            return False
        l = i
        r = j
        while l <= r:
            if s[l] == s[r]:
                l += 1
                r -= 1
            else:
                return False
            
        return True

Java

必须掌握基础方法!
注意:使用ArrayList删除尾元素比LinkedList要快很多!!!

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        if (s.length() == 0) {
            return res;
        }
        List<String> tmp = new ArrayList<>();
        dfs(s, 0, tmp, res);

        return res;
    }

    public void dfs(String s, int startIndex, List<String> tmp, List<List<String>> res) {
        if (startIndex == s.length()) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = startIndex; i < s.length(); ++i) {
            if (!valid(s, startIndex, i)) {
                continue;
            }
            tmp.add(s.substring(startIndex, i + 1));
            dfs(s, i + 1, tmp, res);
            tmp.remove(tmp.size() - 1);
        }
    }

    public boolean valid(String s, int startIndex, int endIndex) {
        while (startIndex <= endIndex) {
            char left = s.charAt(startIndex);
            char right = s.charAt(endIndex);
            if (left != right) {
                return false;
            }
            ++startIndex;
            --endIndex;
        }

        return true;
    }
}

法2:DFS+回文串判断预处理

主要优化回文串判断部分
在这里插入图片描述

Python

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        n = len(s)
        judge = [[False]*n for _ in range(n)]
        for i in range(n):
            judge[i][i] = True
        for i in range(n-2, -1, -1):
            for j in range(i+1, n):
                if s[i] == s[j] and (j-i == 1 or judge[i+1][j-1]):
                    judge[i][j] = True
                else:
                    judge[i][j] = False
        
        res = list()
        tmp = list()
        self.dfs(0, s, tmp, res, judge)
        return res
    
    def dfs(self, idx, s, tmp, res, judge):
        if idx == len(s):
            res.append(tmp.copy())
        
        for i in range(idx, len(s)):
            if judge[idx][i]:
                tmp.append(s[idx: i+1])
                self.dfs(i+1, s, tmp, res, judge)
                tmp.pop()

Java

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        int n = s.length();
        boolean[][] dp = new boolean[n][n]; // dp[i][j]表示s[i:j]之间是回文串
        for (int i = 0; i < n; ++i) {
            dp[i][i] = true;
        }
        for (int i = n - 1; i >= 0; --i) {
            for (int j = i + 1; j < n; ++j) {
                dp[i][j] = (s.charAt(i) == s.charAt(j)) && (j - i == 1 || dp[i + 1][j - 1]);
            }
        }
        List<String> tmp = new ArrayList<>();
        dfs(s, res, tmp, dp, 0);

        return res;
    }

    public void dfs(String s, List<List<String>> res, List<String> tmp, boolean[][] dp, int curInx) {
        if (curInx == s.length()) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = curInx; i < s.length(); ++i) {
            if (dp[curInx][i]) {
                tmp.add(s.substring(curInx, i + 1));
                dfs(s, res, tmp, dp, i + 1);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值