美文网首页
leetcode--19. palindrome-partit

leetcode--19. palindrome-partit

作者: yui_blacks | 来源:发表于2018-12-13 00:10 被阅读0次

题目:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
给定字符串s,分区的每个子字符串都是回文。返回s的所有可能的回文分区。

For example, given s ="aab",
Return
[
["aa","b"],
["a","a","b"]
]

思路:
如果要求输出所有可能的解,往往都是要用深度优先搜索。如果是要求找出最优的解,或者解的数量,往往可以使用动态规划。

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<String>> partition(String s) {
        ArrayList<ArrayList<String>> res = new ArrayList<>();
        help(res,new ArrayList<String>(),s);
        return res;
    }
    private void help(ArrayList<ArrayList<String>> res, ArrayList<String> temp, String s) {
        if(s.length() == 0){
            res.add(new ArrayList<>(temp));
            return;
        }
        for (int i = 1; i <= s.length(); i++) {
            String t = s.substring(0, i);
            if(t.equals(new StringBuffer(t).reverse().toString())){ // 判断是否是回文字符串
                temp.add(t);
                help(res,temp,s.substring(i));
                temp.remove(temp.size()-1);
            }
        }
    }
}

相关文章

网友评论

      本文标题:leetcode--19. palindrome-partit

      本文链接:https://www.haomeiwen.com/subject/rzmmhqtx.html