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.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

采用DP来做。为了不重复计算palindrome, 使用一个map 存储从[i,j]是否为palindrome, 是为1, 不是为-1,没有测试过为0.

 1 public class Solution {
 2     ArrayList<ArrayList<String>> result = null;
 3     int[][] map = null;
 4     public ArrayList<ArrayList<String>> partition(String s) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         result = new ArrayList<ArrayList<String>>();
 8         map = new int[s.length()][s.length()]; 
 9         getPartition(s, 0, new ArrayList<String>());
10         return result;
11     }
12     public void getPartition(String s, int pos, ArrayList<String> row){
13         if(pos == s.length()) result.add(row);
14         for(int i = pos; i < s.length(); i ++){
15             if(map[pos][i] == 0){
16                 if(checkPartition(s, pos, i)) map[pos][i] = 1;
17                 else map[pos][i] = -1;
18             }
19             if(map[pos][i] == 1){
20                 row.add(s.substring(pos, i + 1));
21                 getPartition(s, i + 1, new ArrayList<String>(row));
22                 row.remove(row.size() - 1);
23             }
24         }
25     }
26     
27     public boolean checkPartition(String s, int start, int end){
28         for(int i = 0; i < (end - start + 1) / 2; i ++){
29             if(s.charAt(start + i) != s.charAt(end - i)) return false;
30         }
31         return true;
32     }
33 }

 

转载于:https://www.cnblogs.com/reynold-lei/p/3442591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值