LeetCode#648 Replace Words (week14)

来源:互联网 发布:网络启动 编辑:程序博客网 时间:2024/05/29 15:15

week14

题目

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.
这里写图片描述
Note:
The input will only have lower-case letters.
1 <= dict words number <= 1000
1 <= sentence words number <= 1000
1 <= root length <= 100
1 <= sentence words length <= 1000

原题地址:https://leetcode.com/problems/replace-words/description/

解析

题目给出一个数组dict作为存放字典中的字符串,给定一个字符串sentence,要求将sentence以空格分解为子字符串,如果某个子字符串a以dict中的某个字符串b为开头,称b为a的root,用b代替sentence中对应的a,最后将sentence中的子字符串重新连接为一个字符串
大致思路是先将sentence按空格分割为子字符串并存放在数组中,对于每个子字符串,查找dict中是否有字符串是其root,有则以之代替,最后用数组中的字符串及空格重新拼接成新的字符串

代码

class Solution {public:    string replaceWords(vector<string>& dict, string sentence) {        vector<string> words;        spilt(sentence, words);        replace(dict, words);        string rel = "";        for (int i = 0; i < words.size(); ++i) {            rel += words[i];            rel += " ";        }        return rel.substr(0,rel.size() - 1);    }    /*将字符串按空格分解*/    void spilt(string sentence, vector<string>& words) {        int len = sentence.size();        int begin = 0, end = 0;        int last_blank = -1;        while (end < len) {            /*每找到一个空格生成一个子串*/            if (sentence[end] != ' ') {                ++end;            }            else {                last_blank = end;                string ss = sentence.substr(begin, end - begin);                words.push_back(ss);                begin = end + 1;                end = begin;            }        }        /*最后一个子串后面没有空格,单独处理*/        if (last_blank != -1) {            string s = sentence.substr(last_blank + 1, len - last_blank);            words.push_back(s);        }    }    /*对于words中的每个字符串,在dict中查找root并替代*/    void replace(vector<string>& dict, vector<string>& words) {        int len = words.size();        for (int i = 0; i < len; ++i) {            for (int j = 0; j < dict.size(); ++j) {                if (isRoot(dict[j], words[i])) {                    words[i] = dict[j];                    break;                }            }        }    }    /*比较得到字符串str是否以sub开头*/    bool isRoot(string sub, string str) {        int k = 0, j = 0;        while (str[k] == sub[j] && k < str.size() - 1) {            if (j == sub.size() - 1) {                return true;            }            ++k;            ++j;        }        return false;    }};
原创粉丝点击