140 Word Break II
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].template<typename T, typename T2>
void print_v_pair(vector<pair<T, T2>> &ar) {
for (auto i : ar) {
cout << i.first << " ";
}
cout << endl;
for (auto i : ar) {
cout << i.second << " ";
}
cout << endl;
pause();
}
struct Comp {
typedef pair<string, size_t> P;
bool operator() (const P &first, const P &second) {
return first.second < second.second;
}
};
bool isSubstr(string &one, string &two) {
if (one.find(two) == string::npos && two.find(one) == string::npos)
return false;
return true;
}
vector<pair<string, size_t>> intersect(string s, unordered_set<string>& wordDict) {
// getting extra digit for location of string that I can sort later
// that why I can maintain the order of the string
vector<pair<string, size_t>> both;
for (auto i : wordDict) {
size_t found = s.find(i);
if (found != string::npos)
both.push_back(make_pair(i, found));
}
return both;
}
vector<vector<string>> group_substrings(vector<pair<string, size_t>> & strs) {
vector<vector<string>> groups;
vector<string> temp;
for (int i = strs.size() - 1; i >= 0; i--) {
string cur = strs.at(i).first;
temp.push_back(cur);
// move back from current string to check other potential substrings
for (int j = i - 1; j >= 0; j--) {
if (isSubstr(strs.at(j).first, cur)) {
temp.push_back(strs.at(j).first);
}
else {
i = j + 1;
break;
}
}
groups.push_back(temp);
temp.clear();
if (i == 1) break;
}
return groups;
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<pair<string, size_t>> both = intersect(s, wordDict);
sort(both.begin(), both.end(), Comp());
print_v_pair(both);
vector<vector<string>> grouped = group_substrings(both);
print2d(grouped);
for (int i = grouped.size(); i >= 0; i--) {
}
vector<string> sol;
return sol;
}
int main() {
unordered_set<string> map = {
"and", "sand", "cat", "cats", "dog",
};
print(wordBreak("catsanddog", map));
}Last updated