gpt4 book ai didi

c++ - 动态规划 - 分词

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:05:22 27 4
gpt4 key购买 nike

我正在尝试解决 this问题。问题如下
给定一个输入字符串和一个单词字典,看看是否可以将输入字符串分割成以空格分隔的字典单词序列。

字典是一个字符串数组。

我的方法是以下递归 fn 并存储递归调用的结果。输出很好,但我看到存储的结果从未使用过。我的解决方案希望是正确的,因为它通过了测试用例。但如果我知道是否使用 DP,我会很棒。

代码是:

#include <iostream>
#include <string.h>
using namespace std;

int r[100][100] = {0}; //To Store the calculated values


bool searchWord(char q[], char D[][20], int start, int end) {
cout << "In Search Word Loop with " << start << " " << end << endl;
char temp[end - start + 1];
int j = 0;

for (int i = start; i <= end ; ++i) {
//cout << "Looping i " << i << endl;
temp[j] = q[i];
j++;
}

// cout << "For Word " << temp << endl;
for (int i = 0; i < 12; ++i) {
// cout << "Comparing with " << D[i] << endl;
if (!strcmp(temp, D[i])) {
cout << "Found Word" << temp << " " << D[i] << endl;
return 1;
}
}

return 0;
}

bool searchSentence(char q[], char D[][20], int qstart, int qend) {
cout << "In Search Sentence Loop" << endl;
if (r[qstart][qend] != 0) {
cout << "DP Helped!!!" << endl;
return 1;
}

if (qstart == qend) {
if (searchWord(q, D, qstart, qstart))
return 1;
else return 0;
}
if (qstart > qend) return 1;

int i;
for (i = qstart; i <= qend; i++) {
if (searchWord(q, D, qstart, i)) {
r[i + 1][qend] = searchSentence(q, D, i + 1, qend);
if (r[i + 1][qend] == 1) return 1;
}
}

return 0;
}

int main() {
char D[20][20] = { "i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"};
char q[100] = "samsungmango";

int index = 0; char ch;
ch = q[0];
while (ch != '\0') {
index++;
ch = q[index];
}

if (searchSentence(q, D, 0, index - 1))
cout << "Yes" << endl;
else cout << "No" << endl;
}

最佳答案

递归是强制的吗?我明白了,迭代 DP 解决方案是最简单和紧凑的:

#include <stdio.h>
#include <string.h>

int main() {
const char *D[] = { "i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango", NULL};
const char q[] = "samsungmango";
char dp[100];
short d_len[20];
memset(dp, 0, sizeof(dp));
dp[0] = 1; // 0 element is always reacheable
int i, j;
// compute dict string lengths
for(i = 0; D[i]; i++)
d_len[i] = strlen(D[i]);

// Compute splits using DP array
for(i = 0; q[i] != 0; i++)
if(dp[i]) // this index is reacheable
for(j = 0; D[j]; j++) // try to make next reacheable indexes
if(strncmp(&q[i], D[j], d_len[j]) == 0)
dp[i + d_len[j]] = 1; // That position is reacheable, too

// if EOLN(q) is reached, then yes
printf("Answer is %s\n", dp[i]? "YES" : "NO");

} // main

关于c++ - 动态规划 - 分词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168061/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com