lintcode-medium-Palindrome Partition
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example
Given s = "aab"
, return:
[ ["aa","b"], ["a","a","b"] ]
public class Solution { /** * @param s: A string * @return: A list of lists of string */ public List<List<String>> partition(String s) { // write your code here List<List<String>> result = new ArrayList<List<String>>(); if(s == null || s.length() == 0) return result; ArrayList<String> line = new ArrayList<String>(); helper(result, line, 0, s); return result; } public void helper(List<List<String>> result, ArrayList<String> line, int start, String s){ if(start == s.length()){ result.add(new ArrayList<String>(line)); return; } for(int i = start + 1; i <= s.length(); i++){ String temp = s.substring(start, i); if(valid(temp)){ line.add(temp); helper(result, line, i, s); line.remove(line.size() - 1); } } return; } public boolean valid(String s){ int left = 0; int right = s.length() - 1; while(left < right){ if(s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } }