LeetCode.Word Break
来源:互联网 发布:通过手机网络定位 编辑:程序博客网 时间:2024/06/05 00:31
试题请参见: 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"
.
解题思路
DP问题.
使用数组isMatched[i]表示字符串s[0, i - 1]是否可以被划分.
因此isMatched[s.length]表示字符串s是否可以被划分.
若isMatched[i] == true, 表示s[0, i - 1]可以被划分, 则需要同时满足如下条件之一:
isMatched[0] == true
, 且s[0, i - 1]
在dict中isMatched[1] == true
, 且s[1, i - 1]
在dict中isMatched[2] == true
, 且s[2, i - 1]
在dict中- `…
isMatched[i - 1] == true
, 且s[i - 1, i - 1]
在dict中
例如: s = "aaaaa"
, dict = { "aaaa", "aaa" }
.
isMatched[1] == false
, 因为"a"
不在dict中isMatched[2] == false
, 因为"aa"
不在dict中isMatched[3] == true
, 因为"aaa"
在dict中isMatched[4] == true
, 因为"aaaa"
在dict中对于
isMatched[5]
, 因为"aaaaa"
不在dict中- 进而需要判断
isMatched[1] = true
且s[1...4]
在dict中, 显然前者不成立 - 进而需要判断
isMatched[2] = true
且s[2...4]
在dict中, 显然前者不成立 - 进而需要判断
isMatched[3] = true
且s[3...4]
在dict中, 显然后者不成立 - 进而需要判断
isMatched[4] = true
且s[4...4]
在dict中, 显然后者不成立
- 进而需要判断
因此isMatched[5] == false
.
源代码
import java.util.HashSet;import java.util.Set;public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { int length = s.length(); boolean[] isMatched = new boolean[length + 1]; isMatched[0] = true; for ( int i = 1; i <= length; ++ i ) { for ( int j = 0; j < i; ++ j ) { if ( isMatched[j] && wordDict.contains(s.substring(j, i)) ) { isMatched[i] = true; break; } } } return isMatched[length]; } public static void main(String[] args) { Solution s = new Solution(); Set<String> set = new HashSet<String>(); set.add("leet"); set.add("code"); System.out.println(s.wordBreak("leetcode", set)); }}
0 0
- leetcode Word Break & Word Break ||
- Leetcode: Word Break
- [leetcode]Word Break
- [leetcode]Word Break II
- LeetCode:Word Break
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break
- [LeetCode] Word Break II
- LeetCode: Word Break
- leetcode之Word Break
- [LeetCode]Word Break II
- [LeetCode]Word Break
- leetcode-Word Break
- LeetCode 之 Word Break
- leetcode word break
- LeetCode | Word Break
- LeetCode | Word Break II
- pgsql FAQ
- 安全技术目标
- 图片放大由主要由javascript实现
- Java-十种内部排序实现(选择,冒泡,插入,希尔,堆,归并,快速,基数,计数,桶)及代码下载
- C语言设计模式与接口
- LeetCode.Word Break
- JAVA深入研究——Method的Invoke方法
- 【Ray Trace from Groud Up】光线追踪代码实现解析
- 1002. A+B for Polynomials (25)
- 【笔试】53、圆圈中最后剩下的数字(约瑟夫环)
- 关于ios8中CMStepCounter过时的问题
- 纪念碑
- jQuery源码分析之$.map函数
- 用快排思路解决逆序对问题