LeetCode139:Word Break
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 = “l(fā)eetcode”,
dict = [“l(fā)eet”, “code”].
Return true because “l(fā)eetcode” can be segmented as “l(fā)eet code”.
記得最開始做動(dòng)態(tài)規(guī)劃的題時(shí)是打開過這道題的,可是那時(shí)沒什么思路。如今動(dòng)態(tài)規(guī)劃的題刷了不少了,今天再做這道題時(shí)非常快就想出了狀態(tài)和狀態(tài)轉(zhuǎn)移方程。不能不說還是有點(diǎn)進(jìn)步。
定義A[i]表示0到下標(biāo)為i的子字符是否能被切割成dict中的多個(gè)單詞。
那么A[i]與A[j],0<=j< i都有關(guān)系,即A[i]與前A[]中的前i-1項(xiàng)都有關(guān)系,詳細(xì)為:
…..
這樣一直遍歷到A[i-1]位置。
在上面的遍歷過程中假設(shè)遍歷到某一步j(luò),A[j]=1而且j+1到i表示的字符串出如今dict中,表示前j個(gè)字符串能切割成dict中的單詞,j+1到i中的字符串串也能切割成dict中的單詞。這樣表示前i個(gè)字符能被切割成dict中的單詞。
實(shí)際編寫代碼時(shí),j能夠從i開始倒著開始遍歷,這樣能夠降低遍歷的次數(shù)。
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;elsereturn 0;}};轉(zhuǎn)載于:https://www.cnblogs.com/zsychanpin/p/7197159.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode139:Word Break的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 强制将IE8设置为IE7兼容模式来解析网
- 下一篇: 【原】unity shader(3)反射