博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
动态规划之Work Break
阅读量:2343 次
发布时间:2019-05-10

本文共 818 字,大约阅读时间需要 2 分钟。

题目如下:

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".

动态规划的思想就是要根据前面的知识求得全局的最优解,所以该题的解法可如下:

一个boolean数组dp[n+1],其中dp[i]表示字符串s的第0个字符到第i个字符组成的字符串是否在dict中,得到关系式为dp[i] = dp[j] && wordDict.contains(s.substring(j, i))(j < i);

代码如下:

public class Solution {

  public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] arrays = new boolean[s.length() + 1];
arrays[0] = true;
int len = s.length();
for (int i = 1; i <= len; i++) {
for(int j = 0; j < i; j++){
if(arrays[j] && wordDict.contains(s.substring(j, i))){
arrays[i] = true;
break;
}//end if
}//end for j
}//end for i
return arrays[len];
}
}

转载地址:http://qobvb.baihongyu.com/

你可能感兴趣的文章
一些开源项目
查看>>
将博客搬至CSDN
查看>>
MySQL 中事务的实现
查看>>
CheckStyle
查看>>
IDE配置jvm参数
查看>>
内存溢出
查看>>
Spring Cloud 声明式服务调用 Feign
查看>>
JVM实用参数(一)JVM类型以及编译器模式
查看>>
spring cloud config 属性加解密
查看>>
rabbitmq安装
查看>>
RabbitMQ 使用
查看>>
动态代理
查看>>
oracle中merge into用法解析
查看>>
MySQL Explain详解
查看>>
oracle性能监控
查看>>
Spring Boot 整合Servlet
查看>>
Spring Boot 整合Filter
查看>>
nginx 安装
查看>>
ngnix 详解
查看>>
IDEA创建spring boot项目
查看>>