My Java solution. Any thoughts?


  • 0
    X
       public List<List<String>> partition(String s) {
    	return partitionHelper(s, new ArrayList<List<String>>(),
    			new ArrayList<String>());
    }
    
    private List<List<String>> partitionHelper(String s,
    		List<List<String>> result, List<String> list) {
    	if (s.isEmpty()) {
    		result.add(list);
    		return result;
    	}
    
    	for (int i = 0; i < s.length(); i++) {
    		String c = s.substring(0, i + 1);
    		if (isPalindrome(c)) {
    			List<String> branchList = new ArrayList<String>(list);
    			branchList.add(c);
    			result = partitionHelper(s.substring(i + 1), result, branchList);
    		}
    	}
    
    	return result;
    }
    
    private boolean isPalindrome(String s) {
    	StringBuilder reverseS = new StringBuilder(s).reverse();
    	return s.equals(new String(reverseS));
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.