LeetCode Word Break

LeetCode Word Break

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".

题意是给定一个字符串s和由单词组成的字典,将s用空格进行划分(随便划分几段),判断划分后各个字串在dict中是否都存在,若都存在,则返回true,否则返回false。

思路一,动态规划(DP):对于字符串s = "leetcode",对其进行划分的位置可以表示为:_l_e_e_t_c_o_d_e_,其中每个‘_’表示可以进行划分的位置。设定dp数组表示所有可能的划分位置,dp[i]表示由s[0]-s[i-1]组成的字串能否满足题意(这便是子问题),然后叠代此子结构,一直到dp[s.length()],便得到结果。

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> dp(s.length() + 1, false);
	dp[0] = true;

	for (int i = 1; i <= s.length(); i++)
	{
		for (int j = i-1; j >= 0; j--)
		{
			if (dp[j] == true)
			{
				string word = s.substr(j, i-j);
				if (wordDict.find(word) != wordDict.end())
				{
					dp[i] = true;
					break;
				}
			}
		}
	}

	return dp[s.length()];
    }
};

思路二,搜索

bool wordBreak(string s, unordered_set<string>& wordDict) 
{
	queue<int> q;//保存满足要求划分的下标
	unordered_set<int> visited;

	q.push(0);
	while (q.size() > 0)
	{
		int start = q.front();
		q.pop();
		if (visited.find(start) == visited.end())
		{
			visited.insert(start);//标记已访问
			for (int j = start; j<s.size(); j++)//搜索从start开始,所有可能的子串
			{
				string word(s, start, j - start + 1);//从start开始,判断后面的每个可能的子串
				if (wordDict.find(word) != wordDict.end())//子串满足要求,则加入队列
				{
					q.push(j + 1);
					if (j + 1 == s.size())
						return true;
				}
			}
		}
	}

	return false;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值