Palindrome Partitioning——LeetCode

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之后再还原状态,首先确定解由两部分构成,每次只拆分后半部分,验证前半部分,如果前面是回文,则递归拆分并验证后半部分。

注意:DFS之后要还原状态,从上一个合法解之后继续遍历其他可能。

Talk is cheap>>

public class PalindromePartitioning {

    public List<List<String>> partition(String s) {

        List<List<String>> res = new ArrayList<>();

        ArrayList<String> tmp = new ArrayList<>();

        int length = s.length();

        dfs(s, tmp, res, length);

        return res;

    }



    public void dfs(String src, ArrayList<String> tmp, List<List<String>> res, int length) {

        if (length == 0) {

            res.add((ArrayList<String>) tmp.clone());

            return;

        }

        for (int i = 1; i <= src.length(); i++) {

            if (isValid(src.substring(0, i))) {

                tmp.add(src.substring(0, i));

                dfs(src.substring(i, src.length()), tmp, res, length - i);

                tmp.remove(tmp.size() - 1);

            }

        }

    }



    public boolean isValid(String s) {

        if (s == null || s.length() <= 1) {

            return true;

        }

        int i = 0, j = s.length() - 1;

        while (i < j) {

            if (s.charAt(i) != s.charAt(j)) {

                return false;

            }

            i++;

            j--;

        }

        return true;

    }

}

 

 

 

你可能感兴趣的:(partition)