首页 > 其他 > 详细

[LeetCode]Palindrome Partitioning,解题报告

时间:2014-02-10 17:00:17      阅读:333      评论: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"]
]


思路

题目要求分隔s,求出所有可行的结果,一般遇到需要输出所有可能的结果的时候,最简单的方法就是dfs


AC代码

public class Solution {
    public static ArrayList<ArrayList<String>> partition(String s) {
        ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
        ArrayList<String> tmp = new ArrayList<String>();

        if (s == null || s.length() == 0) {
            return res;
        }

        depthFirstSearch(0, s, tmp, res);

        return res;
    }

    public static void depthFirstSearch(int start, String s, ArrayList<String> tmp,
            ArrayList<ArrayList<String>> res) {
        if (start >= s.length()) {
            res.add(new ArrayList<String>(tmp));
        } else {
            for (int i = start; i < s.length(); i++) {
                if (isPalindrome(s, start, i)) {
                    tmp.add(s.substring(start, i + 1));
                    depthFirstSearch(i + 1, s, tmp, res);
                    tmp.remove(tmp.size() - 1);
                }
            }
        }
    }

    public static boolean isPalindrome(String s, int bt, int ed) {
        for (; bt < ed; bt++, ed--) {
            if (s.charAt(bt) != s.charAt(ed)) {
                return false;
            }
        }

        return true;
    }
}


[LeetCode]Palindrome Partitioning,解题报告

原文:http://blog.csdn.net/wzy_1988/article/details/19035925

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!