码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Partitioning

时间:2015-05-01 00:32:38      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

思路:这个题的解题思路和N-Queens那道题类似。最开始的时候,我们用一个循环列举出所有可能的开始状态。分别检查每一个状态是否满足题意。对于满足的开始状态,我们接着对其后续进行检查。

每次检查的时候,1. 检查这个是不是终止状态。对于这道题,就是看我们是不是已经到达s的末尾了。2.如果不是,我们进入循环,对接下来每一个可能的状态进行检查。2.1 如果不符合题意,直接抛弃。2.2 如果符合,进行下一层的递归循环。

感觉说的云里雾里的。。。直接看代码。。。

 1 public List<List<String>> partition(String s) {
 2         List<List<String>> ret = new ArrayList<List<String>>();
 3         if (s == null) {
 4             return ret;
 5         }
 6         ArrayList<String> path = new ArrayList<String>();
 7         dfs(s, 0, path, ret);
 8         return ret;
 9     }
10     
11     private static void dfs(String s, int index, ArrayList<String> path, List<List<String>> ret) {
12         if (index == s.length()) {
13             ret.add(new ArrayList<String>(path));
14             return;
15         }
16         for (int i = index; i < s.length(); i++) {
17             if (!isPalindrome(s.substring(index, i + 1))) {
18                 continue;
19             }
20             path.add(s.substring(index, i + 1));
21             dfs(s, i + 1, path, ret);
22             path.remove(path.size() - 1);
23         }
24     }
25     
26     private static boolean isPalindrome(String s) {
27         int left = 0;
28         int right = s.length() - 1;
29         while (left < right) {
30             if (s.charAt(left) != s.charAt(right)) {
31                 return false;
32             }
33             left++;
34             right--;
35         }
36         return true;
37     }

 




Palindrome Partitioning

标签:

原文地址:http://www.cnblogs.com/gonuts/p/4470154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!