[CareerCup] 18.7 Longest Word 最长的单词

 

5.7 Given a list of words, write a program to find the longest word made of other words in the list. 

 

这道题给了我们一个字符串数组,让我们找到最长的那个单词是由字符串数组中的其他单词组成的,LeetCode上跟类似的题目有Word BreakWord Break II。那么我们首先来想如果是拆分两个单词怎么做,那我们要首先把所有的单词存到哈希表里,然后遍历每个单词,每个位置上都拆分成左右两个字符串,然后看它们是否都在哈希表中存在,都存在的话就表示该单词符合要求。那么对于拆分成多个单词,我可以使用递归来做,我们首先给单词组进行排序,长度长的在前面,我们需要用哈希表建立单词和其是否能拆分的布尔值之间的映射,还有用一个变量is_original_word表示该单词是单词组的单词还是在递归过程中拆分出来的单词,然后从头开始遍历单词,对于每个单词,我们还是从每个位置拆分成左右两边,如果左边的单词在哈希表中存在且其是可以拆分的,那么我们再递归调用右边的单词,如果所有的拆分方法都完成了,该单词还是不能拆成已有的单词,那么将其哈希表中的值赋为false。

 

bool can_build_word(string word, bool is_original_word, unordered_map<string, bool> &m) {
    if (m.count(word) && !is_original_word) return m[word];
    for (int i = 1; i < word.size(); ++i) {
        string left = word.substr(0, i);
        string right = word.substr(i);
        if (m.count(left) && m[left] && can_build_word(right, false, m)) {
            return true;
        }
    }
    m[word] = false;
    return false;
}

string print_longest_word(vector<string> &words) {
    unordered_map<string, bool> m;
    for (auto a : words) m[a] = true;
    sort(words.begin(), words.end(), [](const string &a, const string b){return a.size() > b.size();});
    for (auto a : words) {
        if (can_build_word(a, true, m)) {
            return a;
        }
    }
    return "";
}

 

CareerCup All in One 题目汇总

posted @ 2016-05-08 02:05  Grandyang  阅读(836)  评论(0编辑  收藏  举报
Fork me on GitHub