Palindrome Partitioning

来源:互联网 发布:linux 驱动与 win驱动 编辑:程序博客网 时间:2024/05/21 14:03

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

java

public class Solution {    /*     * @param s: A string     * @return: A list of lists of string     */    public List<List<String>> partition(String s) {        // write your code here        List<List<String>> result = new ArrayList<>();        if (s == null || s.length() == 0) {            return result;        }        List<String> list = new ArrayList<>();        if (s.length() == 1) {            list.add(s);            result.add(list);            return result;        }        dfs(s, 0, list, result);        return result;    }    private void dfs(String s,                     int startIndex,                      List<String> list,                      List<List<String>> result) {        if (startIndex == s.length()) {            result.add(new ArrayList<String>(list));        }        for (int i = startIndex; i < s.length(); i++) {            String sub = s.substring(startIndex, i + 1);            if (!isPalindrome(sub)) {                continue;            } else {                list.add(sub);                dfs(s, i + 1, list, result);                list.remove(list.size() - 1);            }        }    }    private boolean isPalindrome(String s) {        if (s == null || s.length() == 0) {            return false;        }        char[] c = s.toCharArray();        int i = 0;         int j = c.length - 1;        while (i <= j) {            if (c[i++] != c[j--]) {                return false;            }         }        return true;    }}


原创粉丝点击