Sharing my clean Java solution


  • 0
    public class Solution {
        public List<List<String>> partition(String s) {
            List<List<String>> result = new ArrayList<>();
            char[] chars = s.toCharArray();
            List<String> solution = new ArrayList<>();
            helper(0, chars, solution, result);
            return result;
        }
        
        private void helper(int start, char[] chars, List<String> solution, List<List<String>> result) {
            if (start == chars.length) {
                result.add(new ArrayList<>(solution));
                return;
            }
            for (int i = start; i < chars.length; i++) {
                if (isValid(start, i, chars)) {// substring(start -> i) is Palindrome.
                    solution.add(new String(chars, start, i - start + 1));
                    helper(i + 1, chars, solution, result);
                    solution.remove(solution.size() - 1);
                }
            }
        }
        
        private boolean isValid(int start, int end, char[] chars) {
            while (start < end) {
                if (chars[start++] != chars[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.