[Leetcode] #139 Word Break

Discription

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

Solution

/*  
    序列型動態規劃
	dp[i]表示前i個字符能不能被dict完美劃分(注意i和對應字符串中的位置)
	判斷dp[i],則需要遍歷0~i中是否存在一個j,使得dp[j]=true而且s.substr(j,i-j)存在於dict中
	動態轉移方程:dp[i]=dp[j] && s.substr(j,i-j)
*/
bool wordBreak(string s, vector<string>& wordDict) {
	unordered_map<string, int> wordMap;
	for (string str : wordDict)
		wordMap[str]++;
	int len = s.size() + 1;
	vector<bool> dp(len + 1, false);
	dp[0] = true;
	for (int i = 1; i <= len; i++){
		for (int j = i - 1; j >= 0; j--){
			if (dp[j] && wordMap[s.substr(j, i - j)]){
				dp[i] = true;
				break;
			}
		}
	}
	return dp[len];
}
GitHub-Leetcode:https://github.com/wenwu313/LeetCode

發佈了129 篇原創文章 · 獲贊 52 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章