voidclearlove13() { std::unordered_set<std::string> dict = { "你", "学会", "最大匹配算法", "了吗"}; //当作词典 std::string s = "你学会最大匹配算法了吗"; int mx = 0; for (auto &w : dict) { mx = std::max(mx, (int)w.size()); } std::vector<std::string> res; int n = s.size(); for (int i = 0; i < n;) { int len = std::min(mx, n - i); bool ok = false; //逐长度查询 while (len) { std::string cur = s.substr(i, len); if (dict.count(cur)) { res.push_back(cur); i += len; ok = true; break; } len--; } if (!ok) { res.push_back(s.substr(i, 1)); i++; } } for (auto &x : res) { std::cout << x << '\n'; } }
std::vector<std::string> fmm( std::string &s, std::unordered_set<std::string> &dict, int mx) { std::vector<std::string> res; int n = s.size(); for (int i = 0; i < n;) { int len = std::min(mx, n - i); bool ok = false; while (len) { std::string cur = s.substr(i, len); if (dict.count(cur)) { res.push_back(cur); i += len; ok = true; break; } len--; } if (!ok) { res.push_back(s.substr(i, 1)); i++; } } return res; }
std::vector<std::string> bmm( std::string &s, std::unordered_set<std::string> &dict, int mx) { std::vector<std::string> res; int i = (int)s.size() - 1; while (i >= 0) { int len = std::min(mx, i + 1); bool ok = false; while (len) { std::string cur = s.substr(i - len + 1, len); if (dict.count(cur)) { res.push_back(cur); i -= len; ok = true; break; } len--; } if (!ok) { res.push_back(s.substr(i, 1)); i--; } } std::reverse(res.begin(), res.end()); return res; } //单个字符个数 intcount_single(const std::vector<std::string> &v) { int res = 0; for (auto &s : v) { if (s.size() == 1) { res++; } }
return res; }
std::vector<std::string> bidirectional( std::vector<std::string> &f, std::vector<std::string> &b) { if (f.size() < b.size()) { return f; } if (b.size() < f.size()) { return b; } int sf = count_single(f); int sb = count_single(b); if (sf < sb) { return f; } if (sb < sf) { return b; } return f; }