给定字典做分词
2015-11-12 15:52
656 查看
算法: 给定一个字典和一句话,做分词。
Target: 输入字典,输出所有可能的分词结果。
思路: dfs
加速:首先判断是不是这句话里所有的词在字典中都有(Validate)
输出:
我 喜欢 做一个 程序 员
我 喜欢 做一个 程序员
我 喜欢 做 一个 程序 员
我 喜欢 做 一个 程序员
我 喜 欢 做一个 程序 员
我 喜 欢 做一个 程序员
我 喜 欢 做 一个 程序 员
我 喜 欢 做 一个 程序员
Target: 输入字典,输出所有可能的分词结果。
思路: dfs
加速:首先判断是不是这句话里所有的词在字典中都有(Validate)
#include <iostream> #include <stdio.h> #include "vector" #include <set> #include <unordered_set> using namespace std; class Wordsplit { private: vector<string>; bool match(string s, string cur_ele) { int l = cur_ele.length(); // substr复制子字符串,要求从指定位置开始,并具有指定的长度。 // substr表示从0开始到l结束。 if(s.substr(0,l) == cur_ele) { return ture; } return false; } bool validate(string s, unordered_set<string> &dict) { // calculate all alphabets in the query set<char> alpha; for (int i=0; i<s.length(); i++) { alpha.insert(s[i]); } // calculate all alphabets in the dictionary set<char> beta; unordered_set<string>::iterator dict_it; for (dict_it=dict.begin(); dict_it!=dict.end; dict_it++) { for(int i=0; i<(*dict_it).length(); i++) { beta.insert((*dict_it)[i]); } } set<char>::iterator it; for (it = alpha.begin(); it!=alpha.end(); it++) { if (beta.find(*it)==beta.end()) { return false; } } return true; } public: string split(string s, unordered_set<string> &dict, string cur_str) { if (s.length() == 0) { list.push_back(cur_str.substr(0,cur_str.length()-1)); return s; } // cout << s << endl; unordered_set<string>::iterator it; for (it=dict.begin(); it!=dict.end(); it++) { if(match(s,(*it))) { string tmp_str = cur_str; string latter = s.substr(it->length(), s.length()-it->length()); cur_str += (*it) + " "; // add current word to cur_str cur_str += split(latter,dict,cur_set); // split remaining words cur_str = tmp_str; // back to last status } } return "no result"; } vector<string> main(string s, unordered_set<string> &dict) { if (!validate(s,dict)) { return list; } split(s, dict, ""); return list; } }; int main() { Wordsplit s; unordered_set<string> L={"程序员","公务员","员","我","喜","做","程序","一","欢","喜欢","做一个","一个"}; vector<string> V = s.main("我喜欢做一个程序员"); vector<string>::iterator it; for (it=V.begin(); it!=V.end(); it++) { cout << (*it) << endl; } }
输出:
我 喜欢 做一个 程序 员
我 喜欢 做一个 程序员
我 喜欢 做 一个 程序 员
我 喜欢 做 一个 程序员
我 喜 欢 做一个 程序 员
我 喜 欢 做一个 程序员
我 喜 欢 做 一个 程序 员
我 喜 欢 做 一个 程序员
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#获取关键字附近文字算法实例