题解 | #牛牛研究单词#

牛牛研究单词

https://www.nowcoder.com/practice/b0d32cc14af24af2bc901cd7031c367b

#include <string>

class prefixtree {
private:
    vector<int> table;
    prefixtree* next;
public:
    prefixtree() {
        table.resize(26);
        next = nullptr;
    };

    void insert(string s) {
        prefixtree* nextor = this;
        for (auto it : s) {
            nextor->table[it - 'a']++;
            if (nextor->next == nullptr) {
                nextor->next = new prefixtree();
            }
            nextor = nextor->next;
        }
    }

    int count(string s) {
        prefixtree* nextor = this;
        int count;
        if (s.empty()) {
            for(auto it:nextor->table){
                count += it;
            }
        }
        
        for (auto it : s) {
            if (nextor->table[it - 'a'] == 0) return 0;
            else {
                count = nextor->table[it - 'a'];
                nextor = nextor->next;
            }
        }
        return count;
    }
};



class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param words string字符串vector 
     * @param prefix string字符串 
     * @return int整型
     */
    int countWordsWithPrefix(vector<string>& words, string prefix) {
        // write code here
        prefixtree mytree;
        for(int i = 0; i < words.size(); ++i)
        {
            mytree.insert(words[i]);
        }
        return mytree.count(prefix);
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务