博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Word Break II
阅读量:7240 次
发布时间:2019-06-29

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

Well, it seems that many people meet the TLE problem. Well, I use a simple trick in my code to aoivd TLE. That is, each time before I try to break s, I call isBreakable (just wordBreak from Word Break) to see whether it is breakable. If it is not breakable, then we need not move on. Otherwise, we break it using backtracking.

The idea of backtracking is also typical. Start from index 0 of s, each time we see a word that is in wordDict, add it to a temporary string sentence. When we reach the end of the s, add sentence to sentences. Then we need to recover sentence back to its original status before word was added. So I simply record a temporary string temp each time before I add word to sentence and use it to recover the status.

The code is as follows. I hope it to be self-explanatory enough.

1 class Solution { 2 public: 3     bool isWordBreak(string& s, unordered_set
& wordDict) { 4 vector
dp(s.length() + 1, false); 5 dp[0] = true; 6 int minlen = INT_MAX; 7 int maxlen = INT_MIN; 8 for (string word : wordDict) { 9 minlen = min(minlen, (int)word.length());10 maxlen = max(maxlen, (int)word.length());11 }12 for (int i = 1; i <= s.length(); i++) {13 for (int j = i - minlen; j >= max(0, i - maxlen); j--) {14 if (dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) {15 dp[i] = true;16 break;17 }18 }19 }20 return dp[s.length()];21 }22 void breakWords(string s, int idx, unordered_set
& wordDict, string& sol, vector
& res) {23 if (idx == s.length()) {24 sol.resize(sol.length() - 1);25 res.push_back(sol);26 return;27 }28 for (int i = idx; i < s.length(); i++) {29 string word = s.substr(idx, i - idx + 1);30 if (wordDict.find(word) != wordDict.end()) {31 string tmp = sol;32 sol += word + " ";33 breakWords(s, i + 1, wordDict, sol, res);34 sol = tmp;35 }36 }37 }38 vector
wordBreak(string s, unordered_set
& wordDict) {39 string sol;40 vector
res;41 if (!isWordBreak(s, wordDict)) return res;42 breakWords(s, 0, wordDict, sol, res);43 return res;44 }45 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4565214.html

你可能感兴趣的文章
mysteel Sql
查看>>
Dockerfile中的权限问题及工作目录问题(USER WORKDIR)
查看>>
c#文件读取和写入的方式总结
查看>>
Djano XSS的转义
查看>>
springMVC项目的web.xml文件
查看>>
基础不牢,地动山摇 - OSI模型
查看>>
You (root) are not allowed to access to (crontab)
查看>>
win7自动换锁屏壁纸
查看>>
web3.py简介
查看>>
python类库 - threading.Thread 与 多线程实现
查看>>
笔试面试成对出现的一组数,只有一个或两个只出现一次的数字,找到它们。...
查看>>
javaweb学习总结(二十一)——JavaWeb的两种开发模式
查看>>
【51CTO学院三周年】学习改变命运
查看>>
沈阳租车的注意事项
查看>>
javascript表单验证
查看>>
[LeetCode]83. Remove Duplicates from Sorted List
查看>>
[LeetCode]54. Spiral Matrix
查看>>
Linux镜像本地挂载,使用iso做yum源安装
查看>>
windows凭据管理
查看>>
《Inside C#》笔记(完) 程序集
查看>>