Leetcode 139. Word Break (Medium) (cpp)

Leetcode 139. Word Break (Medium) (cpp)

Difficulty: Medium


/*

139. Word Break (Medium)

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

*/
class Solution {
public:
	bool wordBreak(string s, unordered_set<string>& wordDict) {
		vector<bool> t(s.size() + 1, false);
		t[0] = true;
		for (int i = 1; i <= s.size(); i++) {
			for (int j = i - 1; j >= 0; j--) {
				if (t[j]) {
					if (wordDict.find(s.substr(j, i - j)) != wordDict.end()) {
						t[i] = true;
						break;
					}
				}
			}
		}
		return t.back();
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章