将字符串划分为单词—阿里2017笔试编程题

字符串 ilikealibaba

单词组 :6

i

like

ali

liba

baba

alibaba

~~~~~~~~~~~~~~

输出

i like alibaba

要求是添加最少的空格,同时每个单词都在单词组中。


思想:将单词组按长度排序,每次让i定位在剩下字符串的最左边,j从字符串最右边往左开始遍历单词组,直到匹配,将i-j中的子字符串截取输出。


#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
using namespace std;
void mincut(const string& str, const set& dict)
{
	bool b = false;
	vector vec;
	string s = str;
	string temp, str1, str2, str3 = " ";
	multimap mma;
	int len, n = str.length();
	set::iterator it = dict.begin();
	for (; it != dict.end(); it++) {
		temp = *it;
		len = temp.length();
		mma.insert(pair(len, *it));
	}
	multimap::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 dict;

	cin >> strS;
	cin >> nDict;
	for (int i = 0; i < nDict; i++)
	{
		cin >> dictStr;
		dict.insert(dictStr);
	}
	mincut(strS, dict);
	system("pause");
	return 0;
}


你可能感兴趣的:(将字符串划分为单词—阿里2017笔试编程题)