面试OR笔试8——字符最小分割

61 篇文章 0 订阅
61 篇文章 0 订阅

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;
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值