Palindrome Partitioning
1. Title
Palindrome Partitioning
2. Http address
https://leetcode.com/problems/palindrome-partitioning/
3. The question
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"] ]
4. My code (AC)
1 // Accepted 2 public List<List<String>> partition(String s) { 3 List<List<String>> result = new ArrayList<List<String>>(); 4 if( s == null || s.length() <= 0) 5 return result; 6 int len = s.length(); 7 String subStr= ""; 8 for(int i = 1; i <= len ;i++) 9 { 10 List<String> subRes = new ArrayList<String>(); 11 subStr = s.substring(0, i); 12 if( !isPalindrome(subStr) ) 13 { 14 continue; 15 } 16 subRes.add(subStr); 17 partitionHlper(s,i,subRes,result); 18 } 19 return result; 20 } 21 22 private void partitionHlper(String s, int begin, List<String> subRes, 23 List<List<String>> result) { 24 25 int len = s.length(); 26 if( begin >= len) 27 { 28 result.add(new ArrayList<String>(subRes)); 29 return; 30 } 31 32 String subStr =""; 33 for(int i = begin + 1; i <= len; i++) 34 { 35 subStr = s.substring(begin, i); 36 if( !isPalindrome(subStr) ) 37 { 38 continue; 39 } 40 subRes.add(subStr); 41 partitionHlper(s,i,subRes,result); 42 subRes.remove(subRes.size() - 1); 43 } 44 45 } 46 47 private boolean isPalindrome(String str) { 48 // TODO Auto-generated method stub 49 if( str == null || str.length() <=1) 50 return true; 51 int len = str.length(); 52 int i = 0, j = len -1; 53 while( i < j) 54 { 55 if( str.charAt(i) != str.charAt(j)) 56 { 57 return false; 58 } 59 i++; 60 j--; 61 } 62 return true; 63 }