LeetCode - Replace Words

解法一:vector<vector<string>>

1. vector<vector<string>> v(26) - 26 elements的vector

a. 每一个element里面存相对应字母开头的string; for example, apple是‘a'开头就存在v[0]的vector<string>里

b. 并且按长度的大小顺序存在每个vector<string>里

2. istringstream相当于split

class Solution {
public:
    string replaceWords(vector<string>& dict, string sentence) {
        string res="", t="";
        
        //prepare the vector
        vector<vector<string>> v(26);
        sort(dict.begin(), dict.end(), [](string &a, string &b){return a.size()<b.size();});
        for(string w: dict){
            v[w[0]-'a'].push_back(w);
        }
        
        istringstream is(sentence);
        while(is>>t){
            for(string w:v[t[0]-'a']){
                if(t.substr(0, w.size())==w){
                    t=w;
                    break;
                }
            }
            res += t + " ";
        }
        res.pop_back();
        return res;    
    }
};

解法二:Trie

choice

a.pass in TrieNode*

b.use TrieNode* as a private variable

class Solution {
public:
    class TrieNode{
    public:
        TrieNode* child[26];
        bool isWord;
        TrieNode(): isWord(false){
            for(auto &a: child){
                a=NULL;
            }
        }
    };
    string replaceWords(vector<string>& dict, string sentence) {
        TrieNode* head = new TrieNode();
        for(string w: dict){
            insert(head, w);
        }
        
        string res="", t="";
        istringstream is(sentence);
        while(is>>t){
            if(!res.empty()) res+=" ";
            res += findPrefix(head, t);
        }
        return res;
    }
    void insert(TrieNode* head, string word){
        for(char c: word){
            int pos = c-'a';
            if(!head->child[pos]){
                head->child[pos] = new TrieNode();
            }
            head = head->child[pos];
        }
        head->isWord = true;
    }
    string findPrefix(TrieNode* head, string word){
        string cur="";
        for(char c: word){
            int pos = c-'a';
            if(!head->child[pos]) break;
            cur += c;
            head = head->child[pos];
            if(head->isWord) return cur;
        }
        return word;
    }
};

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/89079464