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

题解:

 1 /*
 2     题意:
 3     给定一个字符串和词典。输出字符串是否能被分割成一个或多个词典中包含的单词。
 4     
 5     思路:
 6     1.原问题满足:
 7         * 最优子结构:问题(s是否可以拆分成多个单词)可以分解为其每个子串是否能拆分为多个单词,如果每个子串都能拆分,则原串也能被拆分。
 8         * 重叠子问题:有一些串会被反复计算是否能拆分
 9     2.动态规划
10     3.递推关系式:
11         f(i)表示前i个字符组成的字符串能否拆分成单词
12         f(i) = f(j) && f(j+1,i) 0<=j<i<=length
13 */
14 #include<unordered_set>
15 using namespace std;
16 class Solution {
17 public:
18     bool wordBreak(string s, unordered_set<string> &dict) {
19         int length = s.length();
20         //dp[i]表示前i个字符可被拆分成单词
21         vector<bool> dp(length + 1);
22         dp[0] = true;
23         for (int pos = 0; pos <= length; pos++) {
24             for (int i = pos + 1; dp[pos] && i <= length; i++) {
25                 if (dict.find(s.substr(pos, i - pos)) != dict.end()) {
26                     dp[i] = true;
27                 }
28             }
29         }
30         return dp[length];
31     }
32 };

猜你喜欢

转载自www.cnblogs.com/yfzhou/p/9639953.html
今日推荐