[leetcode] Word Break

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   使用   ar   for   sp   

1 problem

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".

2 散列容器(hash container)

通常比二叉樹的儲存方式可以提供更高的訪問效率.
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
using namespace boost;
散列集合簡介:
unordered庫提供兩個散列集合類unordered_set和unordered_multiset,STLport也提供hash_set和hash_multiset,
它們的介面,用法與stl裡的標準關聯容器set/multiset相同,只是內部使用散列表代替了二叉樹實現,因此尋找複雜度由數降為常數。

3 Solution1

很自然想到採用遞迴來實現,發現逾時。

bool wordBreak(string s, unordered_set<string> &dict) {    if(dict.find(s) != dict.end()){        return true;                                                                                                                             }        bool finished = false;    for(int i = 1; i< s.length(); i++){        string first = s.substr(0, i);        if(dict.find(first)!=dict.end()){            if(i == s.length()){                finished = true;            }else{                string second = s.substr(i);                finished = wordBreak(second, dict);                if(finished){                    break;                }            }        }    }    return finished;}

給出的例子

Last executed input:

"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]

4 Solution2

昨天看動態規劃,使用條件:

(1)重疊子問題

將一個問題分為若干個子問題的時候,子問題並不是每次都是最新的。因此可以採用空間換時間的方法,將子問題的解記錄下來。

(2)最優子結構

原問題的最優解,包含子問題的最優解。

 

[leetcode] Word Break

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.