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