leetcode 140.单词拆分

#include <iostream>
#include<stdlib.h>
#include<string>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<functional>
#include<queue>
using namespace std;
map<string, int>mymap;//key为元素,value为该元素出现的次数
vector<int>v;//记录字典中每个字符串的长度,并保留唯一,set排序
vector<string>ans;
void print() {
	for (int i = 0; i < ans.size(); i++) {
		cout << ans[i] << " ";
	}
	cout << endl;
}
void wordBreak(string s, vector<string> wordDict) {
	if (s.empty()) {
		print();
		return;
	}
	if (s.length() < v[0])
		return;
	for (int i = 0; i < v.size(); i++) {
		string tmp="";
		if(s.length()>=v[i])
		    tmp = s.substr(0, v[i]);
		if (mymap.find(tmp) != mymap.end()){
			ans.push_back(tmp);
			wordBreak(s.substr(v[i]),wordDict);
			//复原
			ans.pop_back();
		}
	}
}
void getLength(vector<string>wordDict) {
	set<int>length_of_words;
	for (int i = 0; i < wordDict.size(); i++) {
		length_of_words.insert(wordDict[i].length());
		mymap.insert(pair<string,int>(wordDict[i], 1));
	}
	for (set<int>::iterator it = length_of_words.begin(); it != length_of_words.end(); it++) {
		v.push_back(*it);
	}
}
int main() {
	vector<string>wordDict = { "apple", "pen", "applepen", "pine", "pineapple" };
	string str = "pineapplepenapple";
	getLength(wordDict);
	wordBreak(str, wordDict);
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值