Beats 85%


  • 0

    Java

    public class Solution {
    
    	public List<List<String>> partition(String s) {
    		if (s.length() == 0 || s == null)
    			return null;
    		List<List<String>> res = new ArrayList<>();
    		helper(res, new ArrayList<>(), 0, s);
    		return res;
    
    	}
    
    	public void helper(List<List<String>> res, List<String> temp, int start, String s) {
    		if (start == s.length()) {
    			res.add(new ArrayList<>(temp));
    		} else {
    			for (int i = start; i < s.length(); i++) {
    				if (isPalindrome(s, start, i)) {
    					temp.add(s.substring(start, i+1));
    					helper(res, temp, i + 1, s);
    					temp.remove(temp.size() - 1);
    				}
    
    			}
    		}
    	}
    
    	public boolean isPalindrome(String string, int start, int end) {
    		while (start < end) {
    			if (string.charAt(start++) != string.charAt(end--))
    				return false;
    		}
    		return true;
    
    	}
    }
    
    
    
    

Log in to reply
 

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