leetcode 131. Palindrome Partitioning----- java
Posted xiaoba1203
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 131. Palindrome Partitioning----- java相关的知识,希望对你有一定的参考价值。
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 { List list = new ArrayList<ArrayList<String>>(); char[] word ; String ss; String[] result; public List<List<String>> partition(String s) { int len = s.length(); if( len == 0) return list; if( len == 1 ){ ArrayList<String> l1 = new ArrayList<String>(); l1.add(s); list.add(l1); return list; } ss = s; word = s.toCharArray(); result = new String[len]; for( int i = 0;i < len;i++){ if( isPalindrome(0,i) ){ result[0] = s.substring(0,i+1); helper(i+1,1); } } return list; } public void helper(int start,int num){ if( start == word.length ){ ArrayList ll = new ArrayList<String>(); for( int i = 0;i<num;i++) ll.add(result[i]); list.add(ll); return ; } for( int i = start; i < word.length;i++){ if( isPalindrome(start,i) ){ result[num] = ss.substring(start,i+1); helper(i+1,num+1); } } } public boolean isPalindrome(int start,int end){ while( start < end ){ if( word[start] == word[end] ){ start++; end--; }else return false; } return true; } }
以上是关于leetcode 131. Palindrome Partitioning----- java的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 131. Palindrome Partitioning
LeetCode131:Palindrome Partitioning
[leetcode-131-Palindrome Partitioning]
[LeetCode]题解(python):131-Palindrome Partitioning