Palindrome Partition java solution

description:
Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Have you met this question in a real interview? Yes
Example
Given s = “aab”, return:

[
[“aa”,”b”],
[“a”,”a”,”b”]
]

解题思路:因为题目中是要求求出所有的元素的,而且这些元素之间是没有顺序关系的,因此使用DFS。
将题目分为3个步骤
(1)将字符串分割;
(2)判读是否为回文;
(3)返回需要的结果。
注意:代码中的start是表示外层进入循环,用来区分递归的内部进入循环!!!

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 = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return result;
        }
        util(s, 0, result, list);
        return result;
    }
    private void util(String s, 
                      int start,
                      List<List<String>> result,
                      List<String> list) {
        if (start == s.length()) {
            result.add(new ArrayList<String>(list));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            String str = s.substring(start, i + 1);
            if (isPartition(str)) {
                list.add(str);
                util(s, i + 1, result, list);
                list.remove(list.size() - 1);
            }
        }
    }
    private boolean isPartition(String s) {
        if (s.length() == 1) {
            return true;
        }
        for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值