【LeetCode】131. Palindrome Partitioning 分割回文串(Medium)(JAVA)

【LeetCode】131. Palindrome Partitioning 分割回文串(Medium)(JAVA)

题目地址: https://leetcode.com/problems/palindrome-partitioning/

题目描述:

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

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

题目大意

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

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

解题方法

  1. 当前 string 开始遍历,判断前面的 n 个字符是否是回文串,如果是就通过递归把后续子串的分割方案返回
  2. 要注意如果当前整个字符串都是回文串的话,后续没有子串了,就把当前结果整个保存进 list 里面
  3. note: 后续可以对时间优化: 把遍历过 string 用 map 存起来,减少再次遍历
class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            if (!check(s, 0, i)) continue;
            if (i == s.length() - 1) {
                List<String> list = new ArrayList<>();
                list.add(s);
                res.add(list);
                continue;
            }
            String cur = s.substring(0, i + 1);
            List<List<String>> next = partition(s.substring(i + 1, s.length()));
            for (int j = 0; j < next.size(); j++) {
                next.get(j).add(0, cur);
                res.add(next.get(j));
            }
        }
        return res;
    }
    
    public boolean check(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) return false;
            start++;
            end--;
        }
        return true;
    }
}

执行耗时:5 ms,击败了31.55% 的Java用户
内存消耗:39.4 MB,击败了87.82% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值