LeetCode 131. Palindrome Partitioning

来源:互联网 发布:c语言简单小游戏 编辑:程序博客网 时间:2024/06/06 05:16

直接使用DFS硬怼微笑

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

java

class Solution {    public List<List<String>> partition(String s) {        List<List<String>> result = new ArrayList<>();        if (s == null || s.length() == 0) {            return result;        }        dfs(s, 0, new ArrayList<String>(), result);        return result;    }        private void dfs(String s, int start, List<String> path, List<List<String>> result) {        if (start == s.length()) {            result.add(new ArrayList<String>(path));            return;        }        for (int i = start; i < s.length(); i++) {            String str = s.substring(start, i + 1);            if (!isPal(str)) {                continue;            } else {                path.add(str);                dfs(s, i + 1, path, result);                path.remove(path.size() - 1);            }         }    }        private boolean isPal(String s) {        if (s.length() == 1) {            return true;        }        int left = 0;        int right = s.length() - 1;        while (left <= right) {            if (s.charAt(left++) != s.charAt(right--)) {                return false;            }        }        return true;    }}