標籤: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