题:https://leetcode.com/problems/palindrome-partitioning/submissions/1
题目
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
思路
题目大意
给你定s,找出所有子串组,该组中的子串都是回文。
解题思路
见 code
code
python 版
import copy
class Solution:
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
result = []
lst = []
self.partitionString(result,s,lst,0)
return result
def partitionString(self,result,s,lst,pos):
if len(s) == pos:
result.append(copy.copy(lst))
return
for i in range(pos + 1,len(s)+ 1):
subString = s[pos:i]
if self.isPalindrome(subString):
lst.append(subString)
self.partitionString(result,s,lst,i)
lst.pop()
def isPalindrome(self,s):
i = 0
j = len(s) - 1
while i<j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
java 版
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
List<String> lst = new ArrayList<>();
partitionString(res,s,lst,0);
return res;
}
public void partitionString(List<List<String>> res,String s,List<String> lst,int pos){
if(s.length() == pos){
res.add(new ArrayList<String>(lst));
return;
}
for(int i = pos + 1;i <= s.length(); i++){
String substr = s.substring(pos,i);
if(isPalindrome(substr)){
lst.add(substr);
partitionString(res,s,lst,i);
lst.remove(lst.size()-1);
}
}
}
public boolean isPalindrome(String s){
for(int i = 0,j = s.length()-1;i<j;i++,j--){
if(s.charAt(i) != s.charAt(j)) return false;
}
return true;
}
}