131. Palindrome Partitioning

JJ·2021년 1월 1일
0

Algorithms

목록 보기
42/114
class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<List<String>>();
        dfs(0, result, new ArrayList<String>(), s);
        return result;
    }

    public void dfs(int start, List<List<String>> result, List<String> currentList, String s) {
        if (start >= s.length()) result.add(new ArrayList<String>(currentList));
        for (int end = start; end < s.length(); end++) {
            if (isPalindrome(s, start, end)) {
                currentList.add(s.substring(start, end + 1));
                dfs(end + 1, result, currentList, s);
                currentList.remove(currentList.size() - 1);
            }
        }
    }

    boolean isPalindrome(String s, int low, int high) {
        while (low < high) {
            if (s.charAt(low++) != s.charAt(high--)) return false;
        }
        return true;
    }
}

Runtime: 7 ms, faster than 77.33% of Java online submissions for Palindrome Partitioning.
Memory Usage: 52.7 MB, less than 57.85% of Java online submissions for Palindrome Partitioning.
Next challenges:

답 베꼈읍니다 ㅠ
진짜 dfs 그만보고 싶네요...

0개의 댓글