My simple Java solution


  • 0
    R
    public class Solution {
        public List<List<String>> partition(String s) {
            List result = new ArrayList();
            if (s == null || s.length() == 0) {
                return result;
            }
            
            helper(s, result, new ArrayList<String>(), 0);
            
            return result;
        }
        
        private void helper(String s, List result, List<String> solution, int pos) {
            int len = s.length();
            if (pos == len) {
                result.add(new ArrayList<String>(solution));
                return;
            }
            
            for (int i = pos + 1; i <= len; i++) {
                String subString = s.substring(pos, i);
                if (!isValid(subString)) {
                    continue;
                }
                solution.add(subString);
                helper(s, result, solution, i);
                solution.remove(solution.size() - 1);
            }
        }
        
        private boolean isValid (String str) {
            
            if (str == null || str.length() == 0) {
                return false;
            }
            int start = 0;
            int end = str.length() - 1;
            while (start < end) {
                if (str.charAt(start) != str.charAt(end)) {
                    return false;
                }
                start++;
                end--;
            }
            return true;
        }
        
    }

Log in to reply
 

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