题目:

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. np.eye()

    今天在完成深度学习的相关编程作业的时候,发现代码中出现了一个关于np.eye()的函数,这个函数的用法非常的简单,但是在预制的代码中,这个函数的用法并非单单制造一个对角矩阵,而是通过其来将一个labe ...

  2. 【校招面试 之 C/C++】第2题 函数模板、类模板、特化、偏特化

    1.C++模板 说到C++模板特化与偏特化,就不得不简要的先说说C++中的模板.我们都知道,强类型的程序设计迫使我们为逻辑结构相同而具体数据类型不同的对象编写模式一致的代码,而无法抽取其中的共性,这样 ...

  3. OC - runtime - 1

  4. handler------post传送方式

    package com.qianfeng.gp08_day26_hanlder2; import android.os.Bundle; import android.os.Handler; impor ...

  5. catkin-tools

    http://catkin-tools.readthedocs.io/en/latest/cheat_sheet.html 一.Initializing Workspaces初始化工作空间 初始化具有 ...

  6. APScheduler 浅析

    前言 APScheduler是python下的任务调度框架,全程为Advanced Python Scheduler,是一款轻量级的Python任务调度框架.它允许你像Linux下的Crontab那样 ...

  7. sdk接入

    文档 http://blog.csdn.net/chenjie19891104/article/details/42217281 视频: https://chuanke.baidu.com/v2869 ...

  8. linux下安装php php-fpm(转载)

    centos安装php php-fpm 1.下载php源码包http://www.php.net/downloads.php2 .安装phptar -xvf php-5.5.13.tar.bz2cd ...

  9. 2018.07.04 POJ 1696 Space Ant(凸包卷包裹)

    Space Ant Time Limit: 1000MS Memory Limit: 10000K Description The most exciting space discovery occu ...

  10. hdu-1728(bfs+优化)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1728 注意:1.先输入起点(y1,x1)和终点(y2,x2): 2.如果一个一个遍历会超时. 思路:每 ...