当前位置: 首页 > news >正文

OJ练习第158题——单词拆分 II

单词拆分 II

力扣链接:140. 单词拆分 II

题目描述

给定一个字符串 s 和一个字符串字典 wordDict ,在字符串 s 中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。

注意:词典中的同一个单词可能在分段中被重复使用多次。

示例

示例 1:

输入:s = “catsanddog”, wordDict = [“cat”,“cats”,“and”,“sand”,“dog”]
输出:[“cats and dog”,“cat sand dog”]
示例 2:

输入:s = “pineapplepenapple”, wordDict = [“apple”,“pen”,“applepen”,“pine”,“pineapple”]
输出:[“pine apple pen apple”,“pineapple pen apple”,“pine applepen apple”]
解释: 注意你可以重复使用字典中的单词。
示例 3:

输入:s = “catsandog”, wordDict = [“cats”,“dog”,“sand”,“and”,“cat”]
输出:[]

Java代码

class Solution {private List<String> tem = new ArrayList<>();private List<String> res = new ArrayList<>();public List<String> wordBreak(String s, List<String> wordDict) {dfs(0, wordDict, s);return res;}public void dfs(int start, List<String> wordDict, String s) {if(start >= s.length()) {StringBuilder sb = new StringBuilder();for(String ar : tem) sb.append(ar + " ");res.add(sb.toString().trim());return;}for(int i = start; i < s.length(); i++) {if(wordDict.contains(s.substring(start, i + 1))) {tem.add(s.substring(start, i + 1));dfs(i + 1, wordDict, s);if(!tem.isEmpty()) {tem.remove(tem.size() - 1);}}}}
}
http://www.lryc.cn/news/150679.html

相关文章:

  • ArcGIS地块面积分割调整工具插件
  • 基于Matlab实现多个图像增强案例(附上源码+数据集)
  • 计算机网络 概述部分
  • 使用DOSBOX运行TurboC2,TC2使用graphics库绘图
  • OpenCV(二):认识Mat容器
  • springboot整合Excel填充数据
  • c语言技术面试记录 ---- 纲要、题目、分析及给分标准
  • 前端进阶之——模块化
  • Python爬虫抓取表情包制作个性化聊天机器人
  • 使用pip命令安装库,装到其他环境中的问题。
  • 如何使用CSS实现一个带有动画效果的进度条?
  • uni-app 报错 navigateTo:fail page “/pages/.../...“ is not found
  • 【unity插件】使用BehaviorDesigner插件制作BOSS的AI行为树
  • 概念解析 | 量子机器学习:将量子力学与人工智能的奇妙融合
  • 【Cortex-M3权威指南】学习笔记4 - 异常
  • RISC-V(2)——特权级及特权指令集
  • Linux——常用命令大汇总(带你快速入门Linux)
  • 记录 使用 git 克隆仓库报错:Warning: Permanently added‘github.com’ to the .....(ssh )
  • kafka---- zookeeper集群搭建
  • linux安装firefox
  • 【MySQL】基础语法总结
  • 【玩玩Vue】使用el-menu作为菜单时,通过一二级路由控制菜单高亮
  • 9.2 【C语言】使用结构体数组
  • leetcode原题: 最小值、最大数字
  • Prompt2Model: Generating Deployable Models from Natural Language Instructions
  • 前端埋点 sendBeacon 替代方式
  • 面试官问我MySQL和MariaDB的联系和区别,这我能不知道?
  • 1.网络空间搜素引擎
  • 《安富莱嵌入式周报》第321期:开源12导联便携心电仪,PCB AI设计,150M示波器差分探头,谷歌全栈环境IDX,微软在Excel推出Python
  • 前端开发必备的网站