有意义的单词分割——经典dfs题目
680. 分割字符串
中文
English
给一个字符串,你可以选择在一个字符或两个相邻字符之后拆分字符串,使字符串由仅一个字符或两个字符组成,输出所有可能的结果
样例
样例1
输入: "123"
输出: [["1","2","3"],["12","3"],["1","23"]]
样例2
输入: "12345"
输出: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution: """ @param: : a string to be split @return: all possible split string array """ result = [] def splitString( self , s): # write your code here self .split_string_helper(s, start_index = 0 , path = []) return self .result def split_string_helper( self , s, start_index, path): if start_index > = len (s): self .result.append( list (path)) return for step in ( 1 , 2 ): if start_index + step > len (s): # if no this clause, bug for "1" => ["1", "1"] return comb = s[start_index:start_index + step] path.append(comb) self .split_string_helper(s, start_index + step, path) path.pop() |
582. 单词拆分II
中文
English
给一字串s和单词的字典dict,在字串中增加空格来构建一个句子,并且所有单词都来自字典。
返回所有有可能的句子。
样例
样例 1:
输入:"lintcode",["de","ding","co","code","lint"]
输出:["lint code", "lint co de"]
解释:
插入一个空格是"lint code",插入两个空格是 "lint co de"
样例 2:
输入:"a",[]
输出:[]
解释:字典为空
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import sys import json def load_data(): data = json.loads(sys.stdin.read()) return data[ "string" ], set (data[ "word_list" ]) def dfs(s, start, words, arr, results): if start = = len (s): results.append( "," .join(arr)) return for i in range (start, len (s)): word = s[start:i + 1 ] if word in words: arr.append(word) dfs(s, i + 1 , words, arr, results) arr.pop() def main(): string, words = load_data() results, arr = [], [] start = 0 dfs(string, start, words, arr, results) results.sort() print (json.dumps({ 'results' : results})) if __name__ = = "__main__" : main() |
当然,如果使用cache的话,更快:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution: """ @param: s: A string @param: wordDict: A set of words. @return: All possible sentences. """ def wordBreak( self , s, wordDict): # write your code here self .cache = {} return [ " " .join(words) for words in self .dfs(s, words_dict = wordDict)] def dfs( self , s, words_dict): if s in self .cache: return self .cache[s] if not s: return [[]] result = [] for i in range ( 0 , len (s)): word = s[:i + 1 ] if word in words_dict: for w in self .dfs(s[i + 1 :], words_dict): result.append([word] + w) self .cache[s] = result return result |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」