[LeetCode] 139 Word Break(BFS统计层数的方法)

时间:2022-03-20 16:18:23

原题地址:

https://leetcode.com/problems/word-break/description/

题目:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

解法:

这道题目利用动态规划做出来,不得不说想法是很巧妙的,我也是参考了网上的代码才AC了。因此,先放代码,等我完全弄懂再补充吧:

class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if(s == "" || s.size() == ) {
return true;
}
unordered_map<int, bool> res;
for (int i = ; i <= s.size(); i++) {
res[i] = false;
}
res[] = true;
for (int i = ; i < s.size(); i++) {
string str = s.substr(, i + );
for (int j = ; j <= i; j++) {
if (res[j] && find(wordDict.begin(), wordDict.end(), str) != wordDict.end()) {
res[i + ] = true;
break;
}
str = str.substr(, str.size() - );
}
}
return res[s.size()];
}
};

2018.1.7更新

另外的做法(其实就是换了一种统计层数的方法):

class Solution {
public:
bool isConnected(string a, string b) {
int num = ;
for (int i = ; i < a.size(); i++) {
if (a[i] != b[i]) num++;
}
return num == ;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int res = ;
queue<string> s;
s.push(beginWord);
while (!s.empty()) {
int size = s.size();
for (int i = ; i < size; i++) {
string str = s.front();
s.pop();
if (str == endWord) {
return res;
}
for (vector<string>::iterator iter = wordList.begin(); iter != wordList.end();) {
if(isConnected(str, *iter)) {
s.push(*iter);
iter = wordList.erase(iter);
} else {
iter++;
}
}
}
res++;
}
return ;
}
};