【Leetcode 139】Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

给定一个目标字符串和一组字符串,判断目标字符串能否拆分成数个字符串,这些字符串都在给定的那组字符串中。

For example, given 
s = “leetcode”, 
dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.

 

#include<iostream>
#include<stdlib.h>
#include<string>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
	bool wordBreak(string s, vector<string>& wordDict) {
		if (wordDict.size() == 0) {
			return false;
		}

		vector<bool> endHere(s.size() + 1, false);
		endHere[0] = true;

		for (int i = 1; i <= s.size(); i++) {
			for (int j = i - 1; j >= 0; j--) {
				if (endHere[j]) {
					string word = s.substr(j, i - j);
					cout << word << endl;
					if (find(wordDict.begin(), wordDict.end(), word) != wordDict.end()) {
						endHere[i] = true;
						break;
					}
				}
			}
		}
		for (int i = 0; i < endHere.size(); i++)
			cout << endHere[i] << ' ';
            cout<<endl;
		return endHere[s.size()];
	}
};

int main() {
	
	string s = "leetcode";
	vector<string> wordDict;
	string s1 = "leet";
	string s2 = "code";
	wordDict.push_back(s1);
	wordDict.push_back(s2);


	Solution so;
	bool zla;
	zla=so.wordBreak(s, wordDict);

	cout << zla << endl;

	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值