标签:
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"] ]
解题思路:
这种题目一看就是DFS的题,中间用到一个 Valid Palindrome 的方法,判断一个string是不是palindrome。
对于每个位置start,取字符串的可能都是从start开始一直到结尾,所以要判断它是不是palindrome,是的话就加入current。对于下面的字符串继续DFS。到结尾了,回溯。
public class Solution { public List<List<String>> partition(String s) { List<List<String>> result = new LinkedList<List<String>>(); if(s.length() == 0) { return result; } dfs(s, result, new LinkedList<String>(), 0); return result; } public void dfs(String s, List<List<String>> result, LinkedList<String> current, int start) { if(current.size() > 0 && !isPalindrome(current.getLast())) { return; } if(start == s.length()) { result.add(new LinkedList(current)); } for(int i = 1; i < s.length() - start + 1; i++) { current.add(s.substring(start, start + i)); dfs(s, result, current, start + i); current.remove(current.size() - 1); } } public boolean isPalindrome(String s) { if(s.length() == 0) { return true; } int start = 0, end = s.length() - 1; while(start < end) { if(s.charAt(start) != s.charAt(end)){ return false; } start++; end--; } return true; } }
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4395863.html