LeetCode Medium Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

Solution

使用深度优先搜索递归,对于一个字符串,分割为两部分s[0...i]s[i+1...s.length - 1],如果第一部分是回文串的话,加入结果中,并对第二部分进行递归深搜。

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
static bool isPalindrome(char* s, int left, int right) {
    while (left <= right) {
        if (s[left] != s[right]) return false;
        left++;
        right--;
    }
    return true;
}

static void dfs(char* s, int** columnSize, int* returnSize, char*** results, int start, int count, char** cur) {
    if (start == strlen(s)) {
        results[*returnSize] = calloc(count, sizeof(char*));
        int i;
        for (i = 0; i < count; i++) {
            results[*returnSize][i] = calloc(strlen(cur[i]) + 1, sizeof(char));
            memcpy(results[*returnSize][i], cur[i], strlen(cur[i]) * sizeof(char));
            results[*returnSize][i][strlen(cur[i])] = '\0';
        }
        (*columnSize)[*returnSize] = count;
        (*returnSize)++;
        return;
    }
    int i;
    for (i = start; i < strlen(s); i++) {
        if (isPalindrome(s, start, i)) {
            cur[count] = calloc(i - start + 2, sizeof(char));
            memcpy(cur[count], s + start, i - start + 1);
            cur[count][i - start + 1] = '\0';
            dfs(s, columnSize, returnSize, results, i + 1, count + 1, cur);
        }
    }
}

char*** partition(char* s, int** columnSizes, int* returnSize) {
    char*** results = calloc(512, sizeof(char**));
    *columnSizes = calloc(512, sizeof(char*));
    *returnSize = 0;
    int count = 0;
    char** cur = calloc(strlen(s), sizeof(char*));
    dfs(s, columnSizes, returnSize, results, 0, count, cur);
    return results;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值