LeetCode131——分割回文串

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/85329938

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/palindrome-partitioning/description/

题目描述:

知识点:回溯

思路:回溯算法

递归函数:private void nextWords(String s, int index, List<String> list);

其定义为在字符串s的第index位置开始寻找下一个回文字符串,list中存放的是之前的所有回文串。递归函数的出口是index指向了第s.length()个字符。

时间复杂度和空间复杂度均与所给字符串s的构成有关。

JAVA代码:

public class Solution {
    List<List<String>> listList = new ArrayList<>();
    public List<List<String>> partition(String s) {
        nextWords(s, 0, new ArrayList<>());
        return listList;
    }
    private void nextWords(String s, int index, List<String> list){
        if(index == s.length()){
            listList.add(new ArrayList<>(list));
            return;
        }
        for(int i = index; i < s.length(); i++){
            String subStr = s.substring(index, i + 1);
            if(isPalindrome(subStr)){
                list.add(subStr);
                nextWords(s, i + 1, list);
                list.remove(list.size() - 1);
            }
        }
    }
    private boolean isPalindrome(String s){
        for(int i = 0; i <= s.length() / 2; i++){
            if(s.charAt(i) != s.charAt(s.length() - 1 - i)){
                return false;
            }
        }
        return true;
    }
}

LeetCode解题报告:

扫描二维码关注公众号,回复: 4757154 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/85329938
今日推荐