131.Palindrome Partitioning

题目链接

题目大意:给出一个字符串,将其划分,使每个子串都是回文串,计算处所有可能的划分情况。

法一(借鉴):很明显的,是要用DFS。这个可以作为一个模板吧,就是划分字符串的所有子串的一个模板。代码如下(耗时9ms):

 1     public List<List<String>> partition(String s) {
 2         List<List<String>> res = new ArrayList<List<String>>();
 3         List<String> tmp = new ArrayList<String>();
 4         dfs(s, res, 0, tmp);
 5         return res;
 6     }
 7     private static void dfs(String s, List<List<String>> res, int start, List<String> tmp) {
 8         //如果找到一种划分情况,则将其接入结果集中
 9         if(start == s.length()) {
10             res.add(new ArrayList<String>(tmp));
11             return;
12         }
13         //寻找每一个可能的回文字符串
14         for(int i = start; i < s.length(); i++) {
15             //判断字符串的其中一个子串,如果是回文
16             if(isPalindrome(s, start, i) == true) {
17                 //将这个回文子串加入结果中,记住substring(start,end),是从start到end-1的字符串。
18                 tmp.add(s.substring(start, i + 1));
19                 //注意,下次划分的子串起始点应该是i+1,因为i已经在上一个子串中了
20                 dfs(s, res, i + 1, tmp);
21                 //回溯移除
22                 tmp.remove(tmp.size() - 1);
23             }
24         }
25     }
26     //判断回文
27     private static boolean isPalindrome(String s, int start, int end) {
28         while(start <= end) {
29             if(s.charAt(start) != s.charAt(end)) {
30                 return false;
31             }
32             start++;
33             end--;
34         }
35         return true;
36     }
View Code

 

posted on 2018-04-11 15:30  二十年后20  阅读(130)  评论(0编辑  收藏  举报

导航