精華區beta Marginalman 關於我們 聯絡資訊
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]; } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.249.242 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1691160022.A.593.html ※ 編輯: yam276 (123.193.249.242 臺灣), 08/04/2023 23:42:39