LeetCode in Erlang

131. Palindrome Partitioning

Medium

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

A palindrome string is a string that reads the same backward as forward.

Example 1:

Input: s = “aab”

Output: [[“a”,”a”,”b”],[“aa”,”b”]]

Example 2:

Input: s = “a”

Output: [[“a”]]

Constraints:

Solution

-spec partition(S :: unicode:unicode_binary()) -> [[unicode:unicode_binary()]].
partition(S) ->
    Len = byte_size(S),
    dfs(S, Len, 0, [], []).

% Base case: when we've processed the entire string
dfs(_S, Len, L, Subs, Ans) when L =:= Len ->
    [lists:reverse(Subs) | Ans];

% Recursive case: try all possible partitions
dfs(S, Len, L, Subs, Ans) ->
    partition_from_position(S, Len, L, L, Subs, Ans).

partition_from_position(S, Len, L, R, Subs, Ans) when R < Len ->
    Substring = binary:part(S, L, R - L + 1),
    NewAns = case is_palindrome(Substring) of
        true -> 
            dfs(S, Len, R + 1, [Substring | Subs], Ans);
        false -> 
            Ans
    end,
    partition_from_position(S, Len, L, R + 1, Subs, NewAns);
partition_from_position(_S, _Len, _L, _R, _Subs, Ans) ->
    Ans.

% Helper function to check if a binary is a palindrome
is_palindrome(Bin) ->
    List = binary_to_list(Bin),
    List =:= lists:reverse(List).
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy