[leetcode]648. Replace Words

[leetcode]648. Replace Words


Analysis

ummmmmmm—— [ummmm~]

In English, we have a concept called root, which can be followed by some other words to form another longer word - let’s call this word successor. For example, the root an, followed by other, which can form another word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
遍历句子里的每个单词,如果单词的第一个字符与dict里面的某个单词一样,就检查这两个单词是否一样,如果一样就用dict里的单词替换掉句子里面的相应单词,因为题目要求替换后的单词要尽可能的短,所以要先对dict里的单词进行排序,至于怎么排序,当然是按照单词的长度进行升序排列~

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/82706293