1. 程式人生 > >Word Break

Word Break

思路 nbsp 空字符 substr ble tco bst bstr spa

139. Word Break

題目鏈接:https://leetcode.com/problems/word-break/#/description

題目大意:給定一個非空字符串s和一個單詞列表wordDict,列表裏的單詞沒有空字符串,並且沒有重復,要求判斷字符串s可否分割成wordDict裏的單詞。

思路:用動態規劃的思想,定義dp[i]為s字符串的子串s.substr(0,i)是否可以被分割成wordDict裏的單詞,那麽狀態轉移方程為dp[i]=true if s.substr(0,i) in wordDict || dp[j]==true && s.substr(j+1,i-j) in wordDict (0<j<i),else dp[i]=false。

算法復雜度分析:時間復雜度O(n^2),空間復雜度O(n)。

代碼:

 1 class Solution {
 2 public:
 3     bool wordBreak(string s, vector<string>& wordDict) {
 4         unordered_set<string> wordSet;
 5         vector<bool> dp(s.size() + 1, false);
 6         dp[0] = true;
 7         for (auto word : wordDict)
8 wordSet.emplace(word); 9 for (int i = 1; i <= s.size(); ++i) 10 for (int j = 0; j < i; ++j) 11 if (dp[j]) { 12 auto word = s.substr(j, i - j); 13 if (wordSet.find(word) != wordSet.end()) { 14 dp[i] = true
; 15 break; 16 } 17 } 18 return dp[s.size()]; 19 } 20 };

評測系統上運行結果:

技術分享

Word Break