2014-04-29 00:20
题目:给定一个长字符串,和一个词典。如果允许你将长串分割成若干个片段,可能会存在某些片段在词典里查不到,有些则查得到。请设计算法进行分词,使得查不到的片段个数最少。
解法:用空间换取时间的动态规划算法,首先用O(n^2)的时间判断每一个片段是否在字典里。这个过程其实可以通过字典树来进行加速,时间上能优化一个阶,不过我没写,偷懒用<unordered_set>代表了字典。之后通过O(n)时间的动态规划,dp[i]表示当前位置的查不到的片段的最少个数。对于懂代码的人,代码说的比文字清楚,所以请看代码。
代码:
// 17.14 Given a dictionary of words, and a long string. You may find a way to cut the string into words, where some of them may or may not be in the dictionary.
// Dynamic programming is a good thing, but trades space in for time.
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std; int main()
{
string data;
unordered_set<string> dict;
vector<vector<bool> > contains;
vector<int> dp;
int i, j;
string s;
int n;
int tmp; while (cin >> data && data != "") {
cin >> n;
for (i = ; i < n; ++i) {
cin >> s;
dict.insert(s);
}
n = (int)data.length(); contains.resize(n);
for (i = ; i < n; ++i) {
contains[i].resize(n);
}
for (i = ; i < n; ++i) {
s = "";
for (j = i; j < n; ++j) {
s.push_back(data[j]);
contains[i][j] = (dict.find(s) != dict.end());
}
} dp.resize(n);
for (i = ; i < n; ++i) {
dp[i] = contains[][i] ? : i + ;
for (j = ; j < i; ++j) {
tmp = dp[j] + (contains[j + ][i] ? : i - j);
dp[i] = dp[i] < tmp ? dp[i] : tmp;
}
} printf("%d\n", dp[n - ]); for (i = ; i < n; ++i) {
contains[i].clear();
}
contains.clear();
dp.clear();
dict.clear();
} return ;
}