给定字典做分词

算法: 给定一个字典和一句话,做分词。
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;
    }
} 

输出:
我 喜欢 做一个 程序 员
我 喜欢 做一个 程序员
我 喜欢 做 一个 程序 员
我 喜欢 做 一个 程序员
我 喜 欢 做一个 程序 员
我 喜 欢 做一个 程序员
我 喜 欢 做 一个 程序 员
我 喜 欢 做 一个 程序员

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值