Java concise backtracking method(similar to word break II)


  • 0
    S
    public class Solution {
        public List<List<String>> partition(String s) {
            List<List<String>> res = new ArrayList<>();
            if (s.length() == 0) {
                return res;
            }
            for (int i = 1; i < s.length(); i++) {
                if (isPalindrome(s.substring(0, i))) {
                    List<List<String>> tmp = partition(s.substring(i));
                    for (List<String> list : tmp) {
                        list.add(0, s.substring(0, i));
                        res.add(list);
                    }
                }
            }
            if (isPalindrome(s)) {
                List<String> l = new ArrayList<>();
                l.add(s);
                res.add(l);
            }
            return res;
        }
        private boolean isPalindrome(String s) {
            if (s.length() == 0) {
                return true;
            }
            int i = 0;
            int j = s.length() - 1;
            while (i < j) {
                if (s.charAt(i) != s.charAt(j)) {
                    return false;
                }
                i++;
                j--;
            }
            return true;
        }
    }
    

Log in to reply
 

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