lintcode-medium-Palindrome Partition

本文介绍了一种递归算法,用于将给定字符串按回文子串进行划分,并返回所有可能的划分组合。通过递归调用和回溯技术实现,确保每个子串都是回文串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Return all possible palindrome partitioning of s.

 

Example

Given s = "aab", return:

[
  ["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>>();
        
        if(s == null || s.length() == 0)
            return result;
        
        ArrayList<String> line = new ArrayList<String>();
        
        helper(result, line, 0, s);
        
        return result;
    }
    
    public void helper(List<List<String>> result, ArrayList<String> line, int start, String s){
        if(start == s.length()){
            result.add(new ArrayList<String>(line));
            return;
        }
        
        for(int i = start + 1; i <= s.length(); i++){
            String temp = s.substring(start, i);
            
            if(valid(temp)){
                line.add(temp);
                helper(result, line, i, s);
                line.remove(line.size() - 1);
            }
        }
        
        return;
    }
    
    public boolean valid(String s){
        int left = 0;
        int right = s.length() - 1;
        
        while(left < right){
            if(s.charAt(left) != s.charAt(right))
                return false;
            
            left++;
            right--;
        }
        return true;
    }
    
}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5350026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值