【LeetCode】#131分割回文串(Palindrome Partitioning)
阿新 • • 發佈:2018-12-20
【LeetCode】#131分割回文串(Palindrome Partitioning)
題目描述
給定一個字串 s,將 s 分割成一些子串,使每個子串都是迴文串。
返回 s 所有可能的分割方案。
示例
輸入: “aab”
輸出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
Description
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”]
]
解法
class Solution { List<List<String>> res = new ArrayList<>(); public List<List<String>> partition(String s) { if(s==null || s.length()==0) return res; helper(s, new ArrayList<>(), 0); return res; } public void helper(String s, List<String> list, int l){ if(l==s.length()){ res.add(new ArrayList<>(list)); return; } for(int i=l; i<s.length(); i++){ if(isPalindrome(s, l, i)){ list.add(s.substring(l, i+1)); helper(s, list, i+1); list.remove(list.size()-1); } } } public boolean isPalindrome(String s, int l, int r){ while(l<r && s.charAt(l)==s.charAt(r)){ l++; r--; } return l>=r; } }