Palindrome Partitioning

来源:互联网 发布:淘宝双11怎么修改价格 编辑:程序博客网 时间:2024/05/20 18:48

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

Return all possible palindrome partitioning of s.

Example

Given s = "aab", return:

[  ["aa","b"],  ["a","a","b"]]
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;    }}


python
class Solution:    """    @param: s: A string    @return: A list of lists of string    """    def partition(self, s):        # write your code here        if s is None or len(s) == 0:            return [[]]        result = []        self.dfs(s, 0, [], result)        return result        def dfs(self, s, startIndex, arr, result):        if startIndex > len(s):            return        if startIndex == len(s):            result.append(list(arr))        for i in range(startIndex, len(s)):            sub = s[startIndex: i + 1]            if not self.isPalindrome(sub):                continue            else:                arr.append(sub)                self.dfs(s, i + 1, arr, result)                arr.pop()        def isPalindrome(self, s):        if s is None:            return False        if len(s) == 1:            return True        start, end = 0, len(s) - 1        while start <= end:            if s[start] != s[end]:                return False            else:                start += 1                end -= 1        return True