首页 > 代码库 > leetcode 131. Palindrome Partitioning----- java
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。