分割回文串

本文介绍了一种字符串回文分割算法,旨在将给定的字符串分割成一系列回文子串,并提供所有可能的分割方案。该算法通过递归方式实现,每次循环检查字符串的子串是否为回文串,如果是,则继续进行分割。

给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。

返回s所有可能的回文串分割方案。

样例

给出 s = "aab",返回

[
  ["aa", "b"],
  ["a", "a", "b"]
]
public class Solution {
    /**
     * @param s: A string
     * @return: A list of lists of string
     */
    public List<List<String>> partition(String s) {
        // write your code here
         List<List<String>> result =  new ArrayList<List<String>>();//用来保存最后的结果
         List<String> temp = new ArrayList<String>();//保存每个分割方案
         judgeStr(s,temp,0,result);
         return result;
    }
    
    //start表示开始寻找回文串的下标
    public void judgeStr(String s, List<String> temp , int start,List<List<String>> result){
        int len = s.length();
        if(start == len){
            result.add(temp);
            return;//当判断到字符串末尾时,表明之前判断的都是回文串,即满足条件
            //将分割的回文串list加入result 结束循环
        }
        for(int i = start;i<len;i++){
            //每一次循环开始时的temp都是空
            if(isStr(s.substring(start,i+1)) == true){//找到回文串
            //要每次都重新定义temp 仅保存当前回文串
            //所以要先加入之前的temp,再加入新找到的回文串
            //相当于temp用来定位上次检测的位置
                List<String> temp1 = new ArrayList<String>();
                temp1.addAll(temp);
                temp1.add(s.substring(start,i+1));
                judgeStr(s,temp1,i+1,result);
            }
        }
    }
    
    public boolean isStr(String str){//判断是否为回文串
        int len = str.length();
        for(int i=0; i<len/2; i++){
            if(str.charAt(i) != str.charAt(len-i-1))
              return false;
        }
        return true;
    }
}

参考:http://blog.youkuaiyun.com/sunny_ran/article/details/50859671
使用 Java 实现分割回文串的问题通常是指将一个字符串分割成一些子串,使每个子串都是回文串,并返回所有可能的分割方案。以下为相关实现及思路: ### 题目描述 这是力扣的第 131 题,难度中等,相关标签有字符串、动态规划、回溯。给定一个字符串 `s`,需要将其分割成一些子串,使每个子串都是回文串,返回 `s` 所有可能的分割方案。回文串是正着读和反着读都一样的字符串。示例如下: - 输入:`s = "aab"`,输出:`[["a","a","b"],["aa","b"]]` - 输入:`s = "a"`,输出:`[["a"]]` 提示为 `1 <= s.length <= 16`,且 `s` 仅由小写英文字母组成 [^3]。 ### 实现方法 #### 方法一:回溯法结合动态规划 ```java import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class Solution { List<List<String>> lists = new ArrayList<>(); Deque<String> deque = new LinkedList<>(); public List<List<String>> partition(String s) { boolean[][] dp = new boolean[s.length()][s.length()]; for (int i = s.length() - 1; i >= 0; i--) { for (int j = i; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { if (j - i <= 1) { dp[i][j] = true; } else if (dp[i + 1][j - 1]) { dp[i][j] = true; } } } } backTracking(dp, s, 0); return lists; } private void backTracking(boolean[][] dp, String s, int startIndex) { // 如果起始位置大于 s 的大小,说明找到了一组分割方案 if (startIndex >= s.length()) { lists.add(new ArrayList<>(deque)); return; } for (int i = startIndex; i < s.length(); i++) { // 如果是回文子串,则记录 if (dp[startIndex][i]) { String str = s.substring(startIndex, i + 1); deque.addLast(str); } else { continue; } // 起始位置后移,保证不重复 backTracking(dp, s, i + 1); deque.removeLast(); } } } ``` 此方法先使用动态规划生成一个二维数组 `dp`,用于记录所有子串是否为回文串。`dp[i][j]` 表示从索引 `i` 到索引 `j` 的子串是否为回文串。然后使用回溯法,从字符串的起始位置开始,尝试所有可能的分割点,当找到一组分割方案时,将其加入结果列表中 [^4]。 #### 方法二:使用双指针判断回文串 ```java import java.util.ArrayList; import java.util.List; public class Solution2 { List<List<String>> result = new ArrayList<>(); List<String> path = new ArrayList<>(); public List<List<String>> partition(String s) { backtrack(s, 0); return result; } private void backtrack(String s, int start) { if (start == s.length()) { result.add(new ArrayList<>(path)); return; } for (int i = start; i < s.length(); i++) { if (isPalindrome(s, start, i)) { path.add(s.substring(start, i + 1)); backtrack(s, i + 1); path.remove(path.size() - 1); } } } private boolean isPalindrome(String s, int left, int right) { while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; } } ``` 该方法使用回溯法,在回溯过程中使用双指针法判断子串是否为回文串。双指针法从子串的两端开始向中间遍历,如果发现字符不相等,则该子串不是回文串;如果遍历完整个子串都没有发现不相等的字符,则该子串是回文串 [^2][^5]。 ### 复杂度分析 - **时间复杂度**:两种方法的时间复杂度都为 $O(n \times 2^n)$,其中 $n$ 是字符串的长度。最坏情况下,字符串的每个可能的分割方案都需要被考虑,而总共有 $2^{n - 1}$ 种可能的分割方案,对于每种方案,需要 $O(n)$ 的时间来判断子串是否为回文串。 - **空间复杂度**:回溯法结合动态规划的空间复杂度为 $O(n^2)$,主要用于存储动态规划的二维数组;使用双指针判断回文串的空间复杂度为 $O(n)$,主要用于递归调用栈和存储路径。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值