当前位置:网站首页>Leetcode 0140. word splitting II
Leetcode 0140. word splitting II
2022-07-28 03:46:00 【Tisfy】
【LetMeFly】140. Word splitting II
Force button topic link :https://leetcode.cn/problems/word-break-ii/
Given a string s And a string dictionary wordDict , In string s Add spaces to construct a sentence , Make all the words in the sentence in the dictionary . In any order Go back to all these possible sentences .
Be careful : The same word in the dictionary may be repeated many times in segments .
Example 1:
Input :s = "catsanddog", wordDict =["cat","cats","and","sand","dog"]Output :["cats and dog","cat sand dog"]
Example 2:
Input :s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] Output :["pine apple pen apple","pineapple pen apple","pine applepen apple"] explain : Note that you can reuse the words in the dictionary .
Example 3:
Input :s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output :[]
Tips :
1 <= s.length <= 201 <= wordDict.length <= 10001 <= wordDict[i].length <= 10sandwordDict[i]Only lowercase letterswordDictAll strings in are Different
Method 1 : State compression ( Binary violence enumeration )
The maximum length of the string to be split is 20 20 20, and 20 × 2 20 = 20 , 971 , 520 20\times 2^{20}=20,971,520 20×220=20,971,520, Plus in many cases, it will soon break( Unless the data of specially made card data ), Therefore, the operation can be completed within the specified time .
When it comes to state compression , This problem is related to 131. Split palindrome string The solution is very similar .
And (https://leetcode.letmefly.xyz/2022/07/23/LeetCode 0131. Split palindrome string /)[https://leetcode.letmefly.xyz/2022/07/23/LeetCode%200131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2/] The solution is the same , First of all, we use i i i Enumerate which subscript to cut .
The length is n n n There are a total of n − 1 n-1 n−1 A place to cut .
After use j j j from 0 0 0 To n − 1 n-1 n−1, Look at this. n − 1 n-1 n−1 Which of the three cutting positions actually cuts . Then compare the cut substring with the dictionary , See if it exists in the dictionary . If all substrings exist in dictionary , Then use spaces to connect all substrings in this cutting mode , And count in the answer .
- Time complexity O ( n × 2 n ) O(n\times 2^n) O(n×2n), among n n n Is the length of the string . The time complexity of binary state compression enumeration is 2 n 2^n 2n, For an enumeration ( Cutting method ), You need to determine whether each substring of this cutting method is in the dictionary , Time complexity O ( n ) O(n) O(n)( The time complexity of hash table can be regarded as O(1))
- Spatial complexity O ( m + n ) O(m + n) O(m+n), among m m m Is the number of all characters in the dictionary . Binary state compression is compared to recursive state compression , The advantage is that recursion is not required ( Therefore, there is no need to consume recursive space ), The answer is not included in the complexity of the algorithm , Therefore, the space complexity outside the dictionary is only the additional space required for a single enumeration O ( n ) O(n) O(n)
AC Code
C++
#define judge(thisWord) \ if (!st.count(thisWord))\ goto loop;\ thisBreak.push_back(thisWord);
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> ans;
unordered_set<string> st;
for (string& s : wordDict) {
st.insert(s);
}
int n = s.size() - 1;
for (int i = 0; i < (1 << n); i++) {
vector<string> thisBreak;
string toInsert;
string thisWord;
int last = 0;
for (int j = 0; j < n; j++) {
if (i & (1 << j)) {
thisWord = s.substr(last, j - last + 1);
judge(thisWord);
last = j + 1;
}
}
thisWord = s.substr(last, s.size() - last);
judge(thisWord);
for (int i = 0; i < thisBreak.size(); i++) {
if (i)
toInsert += ' ';
toInsert += thisBreak[i];
}
ans.push_back(toInsert);
loop:;
}
return ans;
}
};
Synchronous posting on CSDN, Originality is not easy. , Reprint please attach Link to the original text Oh ~
Tisfy:https://letmefly.blog.csdn.net/article/details/126016024
边栏推荐
- Advanced Mathematics (Seventh Edition) Tongji University exercises 3-6 personal solutions
- Greedy - 53. Maximum subarray sum
- 8000 word explanation of OBSA principle and application practice
- 构建“产业大脑”,以“数字化”提升园区运营管理及服务能力!
- 动态规划——62. 不同路径
- WordPress简约mkBlog博客主题模板v2.1
- What is tor? What is the use of tor browser update?
- 服务器内存故障预测居然可以这样做!
- Super nice PHP program source code of nteam official website
- 面试必备杀技:SQL查询专项训练!
猜你喜欢

ES6 从入门到精通 # 09:Symbol 类型

单调栈——739. 每日温度

Volvo: what on earth does the deep-rooted "sense of security" rely on?

MySQL Basics (create, manage, add, delete, and modify tables)

Mouse operation and response

一文读懂Plato Farm的ePLATO,以及其高溢价缘由

常用的接口测试工具

leetcode刷题:动态规划09(最后一块石头的重量 II)

An article grasps the calculation and processing of date data in PostgreSQL

Leetcode brush question: dynamic planning 09 (weight of the last stone II)
随机推荐
接口自动化测试,完整入门篇
Greedy - 53. Maximum subarray sum
【力扣】1337.矩阵中战斗力最弱的k行
Xctf attack and defense world web master advanced area php2
Use of custom annotations
Recursion and non recursion are used to calculate the nth Fibonacci number respectively
Push chart written by helm to harbor warehouse
Selenium--WEB自动化测试工具
贪心——122. 买卖股票的最佳时机 II
【图像分类】2021-MLP-Mixer NIPS
动态规划——509. 斐波那契数
基于SSM实现在线租房系统
Vertical align align the elements in the row are vertically centered
LabVIEW loads and uses custom symbols in tree control projects
Swift中的协议
MSGAN用于多种图像合成的模式搜索生成对抗网络---解决模式崩塌问题
贪心——45. 跳跃游戏 II
ES6 from getting started to mastering 09: symbol type
Jumping game II in question 45 of C language power deduction. Ergodic jump
超好用的 PC 端长截图工具