-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139.单词拆分.cpp
38 lines (38 loc) · 851 Bytes
/
139.单词拆分.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
* @lc app=leetcode.cn id=139 lang=cpp
*
* [139] 单词拆分
*/
#include "a_header.h"
// @lc code=start
class Solution
{
public:
bool wordBreak(string s,
vector<string> &wordDict)
{
unordered_set<string> dict;
vector<bool> dp(s.length() + 1, false);
dp[0] = true;
for (string &word : wordDict)
{
dict.insert(word);
}
for (int i = 0; i < s.length(); i++)
{
string tmp;
for (int j = i; j >= 0; j--)
{
tmp = s.substr(j, i - j + 1);
if (dict.find(tmp) != dict.end() &&
dp[j])
{
dp[i + 1] = true;
break;
}
}
}
return dp[s.length()];
}
};
// @lc code=end