LeetCode.Word Break
2015-10-06 16:26
190 查看
试题请参见: https://leetcode.com/problems/word-break/
For example, given
s =
dict =
Return true because
使用数组isMatched[i]表示字符串s[0, i - 1]是否可以被划分.
因此isMatched[s.length]表示字符串s是否可以被划分.
若isMatched[i] == true, 表示s[0, i - 1]可以被划分, 则需要同时满足如下条件之一:
`…
例如: s =
对于
进而需要判断
进而需要判断
进而需要判断
进而需要判断
因此
题目概述
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)); } }
相关文章推荐
- 一级指针还是二级指针作函数参数
- 欢迎使用CSDN-markdown编辑器
- mysql免安装的配置方法
- 获取本机 Android 默认sha1 秘钥
- C语言中的高级指针
- 证明 1+1/2+......+1/n不是整数
- hdu 5487 Difference of Languages BFS
- 简介 – ASP.NET MVC 4 系列
- 八大排序算法的 Python 实现
- [Training Video - 3] [Groovy in Detail] What is a groovy class ?
- OC中内存管理之MRC
- ps 命令
- eclipse 断点调试
- 使用多线程模拟多用户并发访问一个或多个tomcat,测试性能 java
- strlen与sizeof
- 关于JavaScript中apply与call的用法意义及区别
- 虚拟化Xen平台中,Dom0和DomU之间发送网络数据时各个部分所运行时间
- centos 6.5 nagios监控安装篇
- UE删除掉所有的重复行
- GO 学习笔记(三) 指针