Palindrome Partitioning

本文介绍了一种使用深度优先搜索(DFS)解决回文字符串划分问题的方法。通过递归加回溯的方式,找到所有可能的回文子串组合,并提供了一个Java实现示例。

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"]
  ]

思路: 题目的要求是求所有的回文划分,因此一定是使用DFS(递归 + 回溯)模板。只需加入判断是否为回文的模块即可。
 1 public class Solution {
 2     /**
 3      * @param s: A string
 4      * @return: A list of lists of string
 5      */
 6     public List<List<String>> partition(String s) {
 7         if (s == null || s.length() == 0) {
 8             return null;
 9         }
10         List<List<String>> result = new ArrayList<>();
11         List<String> path = new ArrayList<>();
12         helper(s, result, path, 0);
13         return result;
14     }
15     private boolean isPalindrome(String s) {
16         int begin = 0;
17         int end = s.length() - 1;
18         while (begin < end) {
19             if (s.charAt(begin) != s.charAt(end)) {
20                 return false;
21             }
22             ++begin;
23             --end;
24         }
25         return true;
26     }
27     private void helper(String s, List<List<String>> result, List<String> path, int pos) {
28         if (pos == s.length()) {
29             result.add(new ArrayList<String>(path));
30                return;
31         }
32         for (int i = pos; i < s.length(); i++) {
33             String prefix = s.substring(pos, i + 1);
34             if (!isPalindrome(prefix)) {
35                 continue;
36             }
37             path.add(prefix);
38             helper(s, result, path, i + 1);
39             path.remove(path.size() - 1);
40         }
41     }
42 }

 

转载于:https://www.cnblogs.com/FLAGyuri/p/5366698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值