[LeetCode]---word-break

来源:互联网 发布:刷棒棒糖辅助软件 编辑:程序博客网 时间:2024/06/15 13:48

题目描述

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

分析

>设数组大小为N;初始化一个数组dp得    vector<bool> dp(N+1,false);    dp[i]表示为字符串s[0...i-1]位置,能否由字典中的词组成,则dp[len]则为最终的解

代码如下

void isWordBreak(string &s,unordered_set<string> &dict, vector<bool> &dp){    for (unsigned long i = 1; i <= s.size(); ++i){        for (int j = i - 1; j >= 0; --j){            if(dp[j]&&dict.find(s.substr(j,i-j))!=dict.end())                dp[i]=true;            }        }    }bool wordBreak(string&s, unordered_set<string> &dict) {       const int N = s.size();       vector<bool> dp(N + 1, false);       dp[0] = true;       isWordBreak(s, dict, dp);       return dp[N];  }
0 0
原创粉丝点击