给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以被空格分割为一个或多个在字典里出现的单词。你可以假设字典中无重复的单词。
例如,给出
s = "leetcode"
,
dict = ["leet", "code"]
。
返回 true 因为 "leetcode"
可以被切分成 "leet code"
。
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"
.
他人思路:
将每个字符串s中的字符当做最后一个要比对的字符,对字典中的每个字符串,与字符串s按顺序取相同字符数量的子串比对。如果相同,且前一个数组中字符串比对结果为true,则此处结果为true。其他位都为false。最终结果以最后一位为准
代码(JavaScript):
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function(s, wordDict) {
var f = new Array(s.length + 1);
f[0]=true;
for(var i = 1; i