如果你想在校招中顺利拿到更好的offer,阿秀建议你多看看前人的经验 ,比如准备 、简历 、实习 、校招总结 、offer选择 、也欢迎来一起参加秋招打卡活动 等;如果你是计算机小白,学习/转行/校招路上感到迷茫或者需要帮助,可以点此联系阿秀;免费分享阿秀个人学习计算机以来的收集到的好资源,点此白嫖;如果你需要《阿秀的学习笔记》网站中求职相关知识点的PDF版本的话,可以点此下载
# 139. 单词拆分
力扣原题链接(点我直达) (opens new window)
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
- 拆分时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
1
2
3
2
3
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
1
2
3
4
2
3
4
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
1
2
2
# 1、经典的DP问题与解法
执行用时:28 ms, 在所有 C++ 提交中击败了58.27%的用户
内存消耗:13.1 MB, 在所有 C++ 提交中击败了48.48%的用户
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.size();
vector<bool> dp(len+1,false);
unordered_set<string> unset(wordDict.begin(), wordDict.end());
dp[0] = true;
for( int i = 1 ; i <= len; ++i ){
for( int j = 0; j < i; ++j ){
if( dp[j] == true && unset.find(s.substr( j, i-j )) != unset.end())
{
dp[i] = true;
break;
}
}
}
return dp[len];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 2、适当优化
对于以上代码可以优化。每次并不需要从s[0]
开始搜索。因为wordDict
中的字符串长度是有限的。只需要从i-maxWordLength
开始搜索就可以了。
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:7.7 MB, 在所有 C++ 提交中击败了100.00%的用户
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.size();
vector<bool> dp(len + 1, false);
unordered_set<string> unset(wordDict.begin(), wordDict.end());
dp[0] = true;
int maxLen=0;
for (int i = 0; i < wordDict.size(); ++i) {
maxLen = max(maxLen, (int)wordDict[i].size());
}
for (int i = 1; i <= len; ++i) {//这里是从1开始的,因为dp[0]无意义
for (int j = max(0,i - maxLen); j < i; ++j) {//这里要有个max的判断,可能在s中还没到最长的长度
if (dp[j] == true && unset.find(s.substr(j, i - j)) != unset.end())
{
dp[i] = true;
break;
}
}
}
return dp[len];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21