Re: [闲聊] 每日LeetCode

楼主: yam276 ('_')   2023-08-04 22:40:20
139. Word Break
Given a string s and a dictionary of strings wordDict, return true if s can be
segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the
segmentation.
算字串是否可以被小字串们拼起来
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
这题好像有很多解法
BackTracking、DP、Memoization都可以的样子
考虑到字串拼图 从字串[0]往字串[n]拼 似乎就是DP了
DP Array只需要一维 从字串第一个字符延伸到尾0到n
每次都是判断0到j的字串(dp[j])能不能被拼+d[j]后面到尾的子字串能不能被拼
并且因为大量存取子字串 用一个hash map来存以减少时间复杂度
Code:
class Solution {
public:
bool wordBreak(string s, vector<string> &wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
int n = s.size();
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordSet.find(s.substr(j, i - j)) != wordSet.end()) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
};

Links booklink

Contact Us: admin [ a t ] ucptt.com