Palindrome Partitioning

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

  ]

采用DP来做。为了不重复计算palindrome, 使用一个map 存储从[i,j]是否为palindrome, 是为1, 不是为-1,没有测试过为0.

 1 public class Solution {

 2     ArrayList<ArrayList<String>> result = null;

 3     int[][] map = null;

 4     public ArrayList<ArrayList<String>> partition(String s) {

 5         // IMPORTANT: Please reset any member data you declared, as

 6         // the same Solution instance will be reused for each test case.

 7         result = new ArrayList<ArrayList<String>>();

 8         map = new int[s.length()][s.length()]; 

 9         getPartition(s, 0, new ArrayList<String>());

10         return result;

11     }

12     public void getPartition(String s, int pos, ArrayList<String> row){

13         if(pos == s.length()) result.add(row);

14         for(int i = pos; i < s.length(); i ++){

15             if(map[pos][i] == 0){

16                 if(checkPartition(s, pos, i)) map[pos][i] = 1;

17                 else map[pos][i] = -1;

18             }

19             if(map[pos][i] == 1){

20                 row.add(s.substring(pos, i + 1));

21                 getPartition(s, i + 1, new ArrayList<String>(row));

22                 row.remove(row.size() - 1);

23             }

24         }

25     }

26     

27     public boolean checkPartition(String s, int start, int end){

28         for(int i = 0; i < (end - start + 1) / 2; i ++){

29             if(s.charAt(start + i) != s.charAt(end - i)) return false;

30         }

31         return true;

32     }

33 }

 

你可能感兴趣的:(partition)