码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Palindrome Partitioning

时间:2016-06-11 02:00:48      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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"]
]

思路:

回溯,判断对每一种切分是否是回文串,剪枝函数是当第一个子串不是回文串时 不往下递归了。

ps:去年做过这题,当时脑子还停留在其他题上,居然想出个用回溯法计算出所有切分的可能,然后对这些切分后的字符串进行判断,= =ORZ


算法:

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

	public List<List<String>> partition(String s) {
		if (s.length() == 0) {
			return results;
		}
		dfs(s, 0, new ArrayList<String>());
		return results;
	}

	public void dfs(String s, int start, List<String> res) {
		if (start == s.length()) {
			results.add(new ArrayList<String>(res));
			return;
		}
		for (int i = start + 1; i <= s.length(); i++) {
			String left = s.substring(start, i);
			if (isPalindrome(left)) {
				res.add(left);
				dfs(s, i, res);
				res.remove(res.size()-1);
			}
		}
	}

	boolean isPalindrome(String s) {
		boolean flag = true;
		int i = 0, j = s.length() - 1;
		char c[] = s.toCharArray();
		while (i < j) {
			if (c[i] != c[j]) {
				flag = false;
				break;
			} else {
				i++;
				j--;
			}
		}
		return flag;
	}


【Leetcode】Palindrome Partitioning

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51629406

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!