字符串 ilikealibaba
单词组 :6
i
like
ali
liba
baba
alibaba
~~~~~~~~~~~~~~
输出
i like alibaba
要求是添加最少的空格,同时每个单词都在单词组中。
思想:将单词组按长度排序,每次让i定位在剩下字符串的最左边,j从字符串最右边往左开始遍历单词组,直到匹配,将i-j中的子字符串截取输出。
#include "stdafx.h"
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <string>
using namespace std;
void mincut(const string& str, const set<string>& dict)
{
bool b = false;
vector<int> vec;
string s = str;
string temp, str1, str2, str3 = " ";
multimap<int, string> mma;
int len, n = str.length();
set<string>::iterator it = dict.begin();
for (; it != dict.end(); it++) {
temp = *it;
len = temp.length();
mma.insert(pair<int, string>(len, *it));
}
multimap<int, string>::reverse_iterator itm;
for (int i = 0; i < n; i++) {
b = false;
for (int j = n-i; j >0; j--) {
temp = str.substr(i, j);
for (itm = mma.rbegin(); itm != mma.rend(); itm++) {
if (!itm->second.compare(temp)) {
b = true;
vec.push_back(i+j);
i = i + j - 1;
break;
}
}
if (b)
break;
}
}
for (int k = 0; k < vec.size(); k++) {
s.insert(vec[k] + k, 1, ' ');
}
cout << s << endl;
}
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);
}
mincut(strS, dict);
system("pause");
return 0;
}