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”.
#include<iostream>
#include<stdlib.h>
#include<string>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if (wordDict.size() == 0) {
return false;
}
vector<bool> endHere(s.size() + 1, false);
endHere[0] = true;
for (int i = 1; i <= s.size(); i++) {
for (int j = i - 1; j >= 0; j--) {
if (endHere[j]) {
string word = s.substr(j, i - j);
cout << word << endl;
if (find(wordDict.begin(), wordDict.end(), word) != wordDict.end()) {
endHere[i] = true;
break;
}
}
}
}
for (int i = 0; i < endHere.size(); i++)
cout << endHere[i] << ' ';
cout<<endl;
return endHere[s.size()];
}
};
int main() {
string s = "leetcode";
vector<string> wordDict;
string s1 = "leet";
string s2 = "code";
wordDict.push_back(s1);
wordDict.push_back(s2);
Solution so;
bool zla;
zla=so.wordBreak(s, wordDict);
cout << zla << endl;
system("pause");
return 0;
}