首页 > 其他 > 详细

Palindrome Partitioning

时间:2015-06-17 02:12:50      阅读:271      评论:0      收藏:0      [点我收藏+]

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

public class Solution {
	public List<List<String>> partition(String s) {
		int len = s.length();
		List<List<String>>[] res = new List[len + 1];
		res[0] = new ArrayList<List<String>>();
		res[0].add(new ArrayList<String>());
		boolean[][] pair = new boolean[len][len];
		for (int i = 0; i < s.length(); i++) {
			res[i + 1] = new ArrayList<List<String>>();
			for (int j = 0; j <= i; j++) {
				if (s.charAt(i) == s.charAt(j)
						&& (i - j < 2 || pair[j + 1][i - 1])) {
					pair[j][i] = true;
					for (List<String> r : res[j]) {
						List<String> ri = new ArrayList<String>(r);
						ri.add(s.substring(j, i + 1));
						res[i + 1].add(ri);
					}
				}
			}
		}
		return res[len];
	}

}
?

Palindrome Partitioning

原文:http://hcx2013.iteye.com/blog/2220195

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!