码迷,mamicode.com
首页 > 其他好文 > 详细

Word Break

时间:2015-02-05 20:30:26      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

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

Return true because "leetcode" can be segmented as "leet code".

解题思路 :用动态规划来解.长度为i的字符串是否包含在字典是有长度j(j<i)的字符串是否包含以及i-j段字符串共同决定.

#include<iostream>
#include<vector>
#include<unordered_set>
using namespace std;

bool IsWord(string s, unordered_set<string> &dict)
{
	unordered_set<string>::iterator Iter = dict.find(s);
	if (Iter == dict.end())
		return false;
	else
		return true;
}
bool wordBreak(string s, unordered_set<string> &dict) {
	vector<bool>FalgWord(s.size()+1,false);
	FalgWord[0] = true;
	for (int i = 0; i <= s.size();++i)
	{
		for (int j = 0; j != i;++j)
		{
			if (FalgWord[i])
				break;
			else
				FalgWord[i] = FalgWord[j] && IsWord(s.substr(j, i - j), dict);
		}
	}
	return FalgWord[s.size()];
}





Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

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

Return true because "leetcode" can be segmented as "leet code".

Word Break

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43532823

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!