设为首页 加入收藏

TOP

[LeetCode] Word Break II
2015-07-20 17:51:39 来源: 作者: 【 】 浏览:2
Tags:LeetCode Word Break

题目链接:https://oj.leetcode.com/problems/word-break-ii/

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].

思路:还是DFS递归遍历。采用动态规划比较麻烦,需要存储当前位置能够实现 word break的所有结果的和,空间复杂度很高,不划算,代码写起来还很麻烦。

public class Solution {
    public List
  
    wordBreak(String s, Set
   
     dict) { List
    
      rsList = new ArrayList
     
      (); if (s == null || s.length() < 1 || dict == null) { return rsList; } wordBreakHelper(s, 0, "", dict, rsList); return rsList; } public void wordBreakHelper(String s, int start, String tempStr, Set
      
        dict, List
       
         rsList) { if (start >= s.length()) { rsList.add(tempStr); return; } for (int i = start + 1; i <= s.length(); i++) { String temp = s.substring(start, i); if (dict.contains(temp)) { String newTempStr; if (tempStr.length() < 1) { newTempStr = temp; } else { newTempStr = tempStr + " " + temp; } wordBreakHelper(s, i, newTempStr, dict, rsList); } } } }
       
      
     
    
   
  

用这个方法还是有一个结果TLE,将WordBreak的方法放到前面先判断一下是否能够word break 后再进行下面的程序就可以AC

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[hdu 4959]Poor Akagi 数论(卢卡.. 下一篇[POJ 2407]Relatives(欧拉函数)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Announcing October (2025-12-24 15:18:16)
·MySQL有什么推荐的学 (2025-12-24 15:18:13)
·到底应该用MySQL还是 (2025-12-24 15:18:11)
·进入Linux世界大门的 (2025-12-24 14:51:47)
·Download Linux | Li (2025-12-24 14:51:44)