Leetcode: Word Break
2014-10-31 08:37
260 查看
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 =
dict =
Return true because
Dynamic Programming: use a boolean array to represent whether the string can be broke from start to that index. Then use the previous status to calculate for the next status.
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
Dynamic Programming: use a boolean array to represent whether the string can be broke from start to that index. Then use the previous status to calculate for the next status.
public class Solution { public boolean wordBreak(String s, Set<String> dict) { if (s == null || s.length() == 0) { return false; } int maxLength = 0; for (String word : dict) { maxLength = Math.max(maxLength, word.length()); } int size = s.length(); boolean[] canBreak = new boolean[size + 1]; canBreak[0] = true; for (int i = 1; i <= size; i++) { canBreak[i] = false; for (int j = 1; j <= maxLength && j <= i; j++) { if (canBreak[i - j]) { String word = s.substring(i - j, i); if (dict.contains(word)) { canBreak[i] = true; break; } } } } return canBreak[size]; } }
相关文章推荐
- LeetCode——Word Break
- [LeetCode] [动态规划] Word Break
- 【LeetCode笔记】Word Break
- leetcode之Word Break
- [leetcode] Word Break
- 【C++】【LeetCode】139. Word Break
- LeetCode 139 Word Break
- [LeetCode]Word Break
- LeetCode 139: Word Break
- Leetcode: Word Break
- leetcode刷题14:word break
- [Leetcode]Word Break
- [LeetCode] Word Break
- [leetcode]Word Break
- Leetcode---Word Break
- Leetcode: Word Break
- LeetCode: Word Break
- LeetCode 139. Word Break(单词分隔)
- LeetCode -- Word Break
- leetcode之Word Break