单词拆分
Leetcode 139
学习记录自代码随想录
要点在注释中详细说明,注意迭代公式中是dp[i]不是dp[j-i]
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>bool wordBreak(char* s, char** wordDict, int wordDictSize) {// 1.dp[j]代表背包容量为字符串s的长度j时是否可以利用字典中单词拼接为字符串s,dp[j]为true和false,bool dp[strlen(s)+1];memset(dp, false, sizeof(dp));// 2.递推公式,if(j到i之间的字符串在wordDict中 && dp[j-i]为true) 则dp[j]为true// 3.dp数组初始化,dp[0] = true;dp[0] = true;// 4.遍历顺序,本题中字符串组合顺序不能改变所以实际上是排列问题,所以先遍历背包,再遍历物品for(int j = 0; j < strlen(s)+1; j++){for(int i = 0; i < j; i++){int length = j - i;char sub_str[length+1];strncpy(sub_str, s+i, length);sub_str[length] = '\0';for(int k = 0; k < wordDictSize; k++){if((strcmp(wordDict[k], sub_str) == 0) && dp[i]){dp[j] = true;}}}}// 5.举例推导dp数组return dp[strlen(s)];
}int main(){int n;scanf("%d", &n);while(n){char s[301];scanf("%s", &s);int wordDictSize;scanf("%d", &wordDictSize);char** wordDict = (char**)malloc((wordDictSize) * sizeof(char*));for(int i = 0; i < wordDictSize; i++){wordDict[i] = (char*)malloc(21 * sizeof(char));scanf("%s", wordDict[i]);}bool result = wordBreak(s, wordDict, wordDictSize);printf("%d", result);for(int i = 0; i < wordDictSize; i++){free(wordDict[i]);}free(wordDict);}return 0;
}