LeetCode139:Word Break,leetcode139break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”.
記得最開始做動態規劃的題時是開啟過這道題的,但是那時沒什麼思路。現在動態規劃的題刷了不少了,今天再做這道題時很快就想出了狀態和狀態轉移方程,不能不說還是有點進步。
定義A[i]表示0到下標為i的子字元能否被分割成dict中的多個單詞。
那麼A[i]與A[j],0<=j< i都有關係,即A[i]與前A[]中的前i-1項都有關係,具體為:
實際編寫代碼時,j可以從i開始倒著開始遍曆,這樣可以減少遍曆的次數。
runtime:4ms
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) { int length=s.size(); int *A=new int[length](); for(int i=0;i<length;i++) { for(int j=i;j>=0;j--) { if(j==i) { A[i]=isExist(s,0,i,wordDict); } else if(A[j]==1) { A[i]=isExist(s,j+1,i,wordDict); } if(A[i]==1) break; } } return A[length-1]==1; } int isExist(string &s,int first,int last,unordered_set<string> &wordDict) { string str=s.substr(first,last-first+1); if(wordDict.count(str)) return 1; else return 0; }};
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。