将给定的字符串分解为字典单词

时间:2016-12-03 16:57:22

标签: c++ algorithm parsing

我试图将给定字符串从给定字典中分解为字典单词并找到所有这些可能的集合。 例如:如果给定的单词是“programmerit”,则输出应为: {{pro,gram,merit},{program,merit},{programmer,it}}

我的下面解决方案,在指数时间内工作。 O(C ^ N);其中c是一些常量,我没有评估,n是给定单词的大小(字符)。 我试图降低复杂性或者可能将其降低到较低的指数,但无济于事。寻找这方面的任何建议。

PS:这不是作业或作业问题,我是一名专业人士,出于好奇而尝试这一点。

这是我的代码:

bool isContained(string word, string s) {
    for (int i = 0; i < s.length(); i++) {
        if (i >= word.length())
            return false;
        if (word[i] != s[i])
            return false;
    }
    return true;
}

    void getParts(vector<string> dict, string word, stack<string> s, vector<vector<string> > &parts) {
        if (word.length() == 0) {
            if (s.size() > 0) {
                vector<string> part;
                stack<string> t = s;
                while(!t.empty()) {
                    part.push_back(t.top());
                    t.pop();
                }
                parts.push_back(part);
            }
        } else {
            int j = find_starting_ind(dict, word[0]);
            int ct = j;
            while (dict[ct][0] == word[0]) {
                if (isContained(word, dict[ct])) {
                    s.push(dict[ct]);
                    string nword = word-dict[ct];
                    getParts(dict, nword, s, parts);
                    s.pop();
                }
                ct++;
            }
        }
    }

0 个答案:

没有答案