Palindrome Partitioning

来源:互联网 发布:淘宝客佣金分成 编辑:程序博客网 时间:2024/04/26 17:19

1.题目

给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。

返回s所有可能的回文串分割方案。

给出 s = "aab",返回

[  ["aa", "b"],  ["a", "a", "b"]]

2.算法

这道题分两步完成

1.先建立一个字典,dict[i][j] i到j的字符串是否是回文

2.字典的结果进行切割,然后按照循环处理递归子问题的方法,如果当前的子串满足回文条件,就递归处理字符串剩下的子串。如果到达字符串末尾,把结果加入

public ArrayList<ArrayList<String>> partition(String s) {      ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();      if(s==null || s.length()==0)     {    return res;    }    helper(s, getDict(s),0,new ArrayList<String>(), res);      return res;  }  public void helper(String s, boolean[][] dict, int start, ArrayList<String> item, ArrayList<ArrayList<String>> res){if (start == s.length()){res.add(new ArrayList<String>(item));return;}for (int i = start; i < s.length(); i++){if (dict[start][i]){item.add(s.substring(start, i + 1));helper(s, dict, i + 1, item, res);item.remove(item.size() - 1);}}}    public boolean[][] getDict(String s) //得到回文字典    {    boolean[][] dict = new boolean[s.length()][s.length()];    for (int i = s.length() - 1; i >= 0; i--)    {    for (int j = i; j < s.length(); j++)    {    if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dict[i + 1][j - 1]))    {    dict[i][j] = true;    }    }    }    return dict;    }


0 0
原创粉丝点击