题目:

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

解题思路:

这是一道DP题,说实话,本人也是算法方面的菜鸟一枚,关于DP方面的题,还不太会解,没办法,只能多练习了。

这里采用DP中的两种方式实现:自顶向下和自底向上。

dp[i]表示前i个字符能否进行Wordbreak。当求解dp[i]时,可利用已经求解的dp[i-1],dp[i-2]…dp[1],dp[0]进行求解。

对于dp[n]的求解,我们可以将n个字符进行切分求解,分为前i个字符和后n-i个字符,i可以为(0,1,2,3,4…n-1)

假设i为1时,可根据dp[i]和后面的n-1个字符组成的单词是否在dict中来判断dp[n],只要i(0,1,2,3,4…n-1)其中一种

情况为真,则dp[n]为true,表示可以进行workbreak。

实现代码:

#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std; /*
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".
*/
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.size() == || dict.size() == )
return false;
int len = s.size();
vector<bool> dp(len+, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread
dp[] = true;
for(int i = ; i <= len; i++)
for(int j = ; j < i; j++)
{
if(dp[j] && dict.count(s.substr(j, i-j)) == )//对前i个字符进行切分时,只要有一种情况为true,则dp[i]=true
{
dp[i] = true;
break;
}
}
return dp[len]; } bool wordBreak2(string s, unordered_set<string> &dict) {
if(s.size() == || dict.size() == )
return false;
int len = s.size();
vector<bool> dp(len+, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread
dp[] = true;
for(int i = ; i < len; i++)
if(dp[i])
{
for(int j = ; j <= len-i; j++)
if(dict.count(s.substr(i, j)) == )
dp[i+j] = true;
} return dp[len]; } //DP:自顶向下,
int wordBreak3_core(string s, unordered_set<string> &dict, int *dp)
{
int len = s.size();
if(dp[len] >= )
return dp[len];//如果值已经改变即不再是初始值,说明dp[len]已经求得,直接返回即可,不必再求
int isBreak;
if(len == )
isBreak = ;
else
{
int ret = ;
for(int i = ; i < len; i++)
{
if(wordBreak3_core(s.substr(, i), dict, dp) == && dict.count(s.substr(i, len-i)) == )
{
ret = ;
break;
} }
isBreak = ret; }
dp[len] = isBreak;
return isBreak;
}
//DP:自顶向下,
bool wordBreak3(string s, unordered_set<string> &dict)
{
if(s.size() == || dict.size() == )
return false;
int len = s.size();
int *dp = new int[len+];//保存状态,dp[i]表示前i个字符是否可以进行wordBread
for(int i = ; i <= len; i++)
dp[i] = -;//每个状态进行初始化
int ret = wordBreak3_core(s, dict, dp);
delete [] dp;
return ret; } }; int main(void)
{
string s("leetcode");
unordered_set<string> dict;
dict.insert("leet");
dict.insert("code");
Solution solution;
bool ret = solution.wordBreak3(s, dict);
cout<<ret<<endl; return ;
}

网上还有通过trie树实现的,这里直接引用http://www.iteye.com/topic/1132188#2402159,就不多写了

代码如下:

class Solution {
public: class Node {
public:
Node* next[];
bool end;
Node(): end(false) { for (int i = ; i < ; i++) next[i] = NULL;}
void insert(string a) {
Node * cur = this;
for (int i = ; i < a.size(); i++) {
if (cur->next[a[i]-'a'] == NULL) {
cur->next[a[i]-'a'] = new Node();
}
cur = cur->next[a[i]-'a'];
}
cur->end = true;
}
~Node () {
for (int i = ;i < ; i++) delete next[i];
}
}; bool wordBreak(string s, unordered_set<string> &dict) {
Node root;
for (auto it = dict.begin(); it != dict.end(); ++it) {
root.insert(*it);
} vector<bool> v(s.size(), false);
findMatch(s, &root, , v);
for (int i = ; i < s.size(); i++)
if (v[i]) findMatch(s, &root, i+, v);
return v[s.size() - ];
} void findMatch(const string& s, Node* cur, int start, vector<bool> &v) {
int i = start, n = s.size();
while (i < n) {
if (cur->next[s[i] - 'a'] != NULL) {
if (cur->next[s[i] - 'a']->end) v[i] = true;
cur = cur->next[s[i] - 'a'];
}
else break;
i++;
} }
};

LeetCode139:Word Break的更多相关文章

  1. LeetCode之“动态规划”:Word Break && Word Break II

     1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...

  2. LeetCode140:Word Break II

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  3. leetcode笔记:Word Break

    一. 题目描写叙述 Given a string s and a dictionary of words dict, determine if s can be segmented into a sp ...

  4. [LeetCode] Word Break II 拆分词句之二

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

  5. word break和word wrap

    默认情况下,如果同一行中某个单词太长了,它就会被默认移动到下一行去: word break(normal | break-all | keep-all):表示断词的方式 word wrap(norma ...

  6. 17. Word Break && Word Break II

    Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...

  7. LeetCode:Word Break II(DP)

    题目地址:请戳我 这一题在leetcode前面一道题word break 的基础上用数组保存前驱路径,然后在前驱路径上用DFS可以构造所有解.但是要注意的是动态规划中要去掉前一道题的一些约束条件(具体 ...

  8. LeetCode Word Break II

    原题链接在这里:https://leetcode.com/problems/word-break-ii/ 题目: Given a string s and a dictionary of words  ...

  9. Leetcode#139 Word Break

    原题地址 与Word Break II(参见这篇文章)相比,只需要判断是否可行,不需要构造解,简单一些. 依然是动态规划. 代码: bool wordBreak(string s, unordered ...

随机推荐

  1. Jmeter分布式

    Jmeter运行时十分耗CPU和内存,在实际应用中有时一台机器不能满足测试要求,这时就需要利用多台机器来进行分布式.   Jmeter分布式的测试框架:框架中所有的测试脚本都要从测试主机传送到测试从机 ...

  2. 平衡二叉树Balanced Binary Tree

    [抄题]: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced b ...

  3. 源码安装php时出现Sorry, I cannot run apxs. Possible reasons follow:

    1.可能的原因是你没有安装perl > yum install perl > yum install httpd-devel 2.在你apache安装目录下的bin下找到apxs,并用vi ...

  4. Halcon的二维码解码步骤和解码技巧

    一.二维码简介 1 . 类型多样,常见的有QR Code二维码. Data Matrix二维码等. 2.高密度编码,信息容量大. 3.容错能力强,具有纠错功能:二维码因穿孔.污损等引起局部损坏时,照样 ...

  5. HDFS高可用性及其分布式系统思想基础

    源自单点失效问题,也就是当NameNode不可用的时候,用什么办法可以平滑过渡? 最直接的办法是再添加一个备用的NN,这就产生了Active NameNode和Standby NameNode的设计思 ...

  6. 20172325 2017-2018-2 《Java程序设计》第七周学习总结

    20172325 2017-2018-2 <Java程序设计>第七周学习总结 教材学习内容总结 1.创建子类 (1) 子类是父类更具体的版本,但子类的实例化不依赖于父类: (2) 继承有单 ...

  7. Spring官方文档翻译(1~6章)

    Spring官方文档翻译(1~6章) 转载至 http://blog.csdn.net/tangtong1/article/details/51326887 Spring官方文档.参考中文文档 一.S ...

  8. Python 的stat 模块

    #!/usr/bin/env python#-*- encoding:UTF-8 -*- import os,time,stat fileStats = os.stat ( 'test.txt' )  ...

  9. div和span元素的区别

    2个都是用来划分区间但是没有实际语义的标签,差别就在于div是块级元素,不会其他元素在同一行;span是内联元素,可以与其他元素位于同一行. DIV 和 SPAN 元素最大的特点是默认都没有对元素内的 ...

  10. QQ使用技巧

    1.改变真实地理位置 大家知道,现在很多QQ都是显示IP和地理位置的版本,这样一来,自己的位置就暴露了.其实想隐藏自己的位置也简单,只要用代理服务器就是了.不要把它看成很复杂的东西,建议去下载&quo ...