leetcode-剑指 Offer II 063. 替换单词

 

 

class Solution {
public:
    // 字符串分割
    vector<string> spltstr(string s){
        vector<string> res;
        string tmp;
        for(auto c: s){
            if(c!=' ')
                tmp = tmp + c;
            else if(c==' '){
                res.push_back(tmp);
                tmp.clear();
            }
    } 
    res.push_back(tmp);
    return res;
    }
    string replaceWords(vector<string>& dictionary, string sentence) {
        vector<string> sen = spltstr(sentence);

        int j;
        for(int i = 0; i < sen.size(); i++){
            int tmp = -1;
            int minlen = INT_MAX;
            for(j = 0; j < dictionary.size(); j++){
                if(dictionary[j]==sen[i].substr(0,dictionary[j].size())){
                    //cout<<j<<" "<<minlen<<endl;
                    if(dictionary[j].size()<minlen){
                        tmp = j;
                        minlen = dictionary[j].size();
                    } 
                }

            }
            // cout<<i<<"  tmp:"<<tmp<<endl;
            if(tmp!=-1)
                sen[i] = dictionary[tmp];
        }
        string res;
        for(auto i : sen)
            res = res + i + " ";
        return res.substr(0,res.size()-1);
    }
};

 

posted @ 2021-09-25 15:09  三一一一317  阅读(61)  评论(0)    收藏  举报