您的位置:首页 > 其它

Leetcode 139 Word Break

2015-06-12 15:55 375 查看
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"
.

数组dp用来表示到该下标处之前的所有字符是否能被字典中的字符串分解。

dp[j] = dp[i] && s[i+1..j] belongs to dictionary

dp的首个值设0以适合一般情况故指针a,b应用到字符串下标都需要-1

def word_break(s, word_dict)
dp = Array.new(s.length+1,false)
dp[0]= true
1.upto(s.length) {|b| b.times {|a| dp[b] = true if dp[a] and word_dict.include?s[a..b-1]}}
dp[-1]
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: