LeetCode139:Word Break,leetcode139break

來源:互聯網
上載者:User

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;        }};

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.