您的位置:首页 > 其它

Leetcode no. 131

2016-05-30 00:47 405 查看
131. 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"]
]


public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res= new LinkedList<>();
List<String> cur= new LinkedList<>();
searchPal(res, cur, s, 0);
return res;
}
private void searchPal(List<List<String>> res, List<String> cur, String s, int pos){
if (pos==s.length()) res.add(new LinkedList<>(cur));
else{
for (int i = pos; i < s.length(); i++) {
if (isPal(s, pos, i)){
cur.add(s.substring(pos,i+1));
searchPal(res, cur, s, i+1);
cur.remove(cur.size()-1);
}
}
}
}
private boolean isPal(String str, int l, int r){
if(l==r) return true;
while(l<r) if(str.charAt(l++)!=str.charAt(r--)) return false;
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: