LeetCode 139. Word Break
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 139. Word Break相关的知识,希望对你有一定的参考价值。
Problem: https://leetcode.com/problems/word-break/
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"
.
Thought:
for each position, traverse whether it is end with word in wordDict, if is ,and check position[i - len] is true. then position[i] = true
the result depend on position[s.length]
Code C++:
class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { if (s.length() <= 0 || wordDict.size() <= 0) { return false; } vector<int> check(s.length() + 1, 0); check[0] = 1; for (int i = 1; i <= s.length(); i++) { for (const string& word : wordDict) { int len = word.length(); if (i - len >= 0 && s.substr(i-len,len) == word && check[i - len] == 1) { check[i] = 1; } } } return check[s.length()] == 1; } };
以上是关于LeetCode 139. Word Break的主要内容,如果未能解决你的问题,请参考以下文章