1 题目及要求
1.1 题目描述
给定一个字符串S和有效单词的字典D,请确定可以插入到S中的最小空格数,使得最终的字符串完全由D中的有效字典组成,并输出解。如果没有解则给出n/a。
输入:
第一行,字符串S
第二行,一个整数n,字典单词数量
第三行,n个单词,空格分开行
输出:
分割后的解
输入范例:
ilikealibaba
6
ilike ali liba baba Alibaba
输出范例:
i like alibaba
2 解答
2.1 代码
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <algorithm>
using namespace std;
string mincut(const string& str, const set<string>& dict, int n){
int sn(str.length());
string res;
int resl = sn<<1;
for( int k1(0); k1 < sn-n; ++k1){
string s1 = str.substr(n,k1+1);
if(dict.find(s1)!=dict.end()){
string s2 = mincut(str,dict,n+k1+1);
if( sn< s2.length()+n+k1+2){
if(s2.length()) s1 += ' ' + s2;
int len = s1.length();
if(len < resl){
res = s1;
resl = len;
}
}
}
}
return res;
}
string mincut(const string& str, const set<string>& dict){
string res = mincut(str,dict,0);
if(res.length()<1) res = "n/a";
return res;
}
int main(int argc, const char * argv[]) {
string strS;
string dictStr;
int nDict;
set<string> dict;
cin>>strS;
cin>>nDict;
for (int i = 0; i < nDict; i++) {
cin>>dictStr;
dict.insert(dictStr);
}
cout << mincut(strS, dict);
return 0;
}