您的位置:首页 > 其它

[LeetCode]131 Palindrome Partitioning

2015-01-08 14:55 411 查看
https://oj.leetcode.com/problems/palindrome-partitioning/
http://blog.csdn.net/linhuanmars/article/details/22777711
public class Solution {
public List<List<String>> partition(String s) {

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

if (s == null || s.isEmpty())
return result;

boolean[][] dict = buildDict(s);
help(s, dict, 0, new ArrayList<String>(), result);
return result;
}

private void help(String s, boolean[][] dict, int start, List<String> item, List<List<String>> result)
{
if (start >= s.length())
{
result.add(new ArrayList<String>(item));
return;
}

for (int i = start; i < s.length() ; i ++)
{
if (!dict[start][i])
continue;

item.add(s.substring(start, i + 1));

help(s, dict, i + 1, item, result);

item.remove(item.size() - 1);
}
}

// dict[i][j] means substring(i, j + 1) is palin
// dict(i, j) = char[i] == char[j] && dict(i + 1, j - 1)
// So i starts from s.length to 0
// j starts from i to s.length
private boolean[][] buildDict(String s)
{
int len = s.length();
boolean[][] dict = new boolean[len][len];

for (int i = len - 1 ; i >= 0 ; i --)
{
for (int j = i ; j < len ; j ++)
{
if (i == j)
dict[i][j] = true;
else if(i + 1 == j)
dict[i][j] = s.charAt(i) == s.charAt(j);
else
dict[i][j] = s.charAt(i) == s.charAt(j) && dict[i + 1][j - 1];
}
}

return dict;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode