[Leetcode] 758. Bold Words in String 解题报告

题目

Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between  and tags become bold.

The returned string should use the least number of tags possible, and of course the tags should form a valid combination.

For example, given that words = ["ab", "bc"] and S = "aabcd", we should return "aabcd". Note that returning "aabcd" would use more tags, so it is incorrect.

Note:

  1. words has length in range [0, 50].
  2. words[i] has length in range [1, 10].
  3. S has length in range [0, 500].
  4. All characters in words[i] and S are lowercase letters.

思路

我们首先定义一个过滤器bolds,用来标记S中哪些字符都已经被加粗了,然后就在S中查找所有的words中的子串,如果找到了,就修改对应的bolds。最后根据过滤器bolds和原字符串S来构造返回结果。

代码

class Solution {
public:
    string boldWords(vector& words, string S) {
        vector bolds(S.length(), false);
        for (string &word : words) {   // try to find word in S
            int start = 0;
            while (start < S.length()) {
                int index = S.find(word, start);
                if (index == string::npos) {
                    break;
                }
                else {
                    for (int i = 0; i < word.length(); ++i) {
                        bolds[i + index] = true;
                    }
                    ++start;
                }
            }
        }
        string ret;
        for (int i = 0; i < S.length(); ++i) {
            if ((i == 0 && bolds[0]) || (i > 0 && !bolds[i - 1] && bolds[i])) {
                ret += "";
            }
            ret.push_back(S[i]);
            if ((i + 1 == S.length() && bolds[i]) || (i + 1 < S.length() && bolds[i] && !bolds[i + 1])) {
                ret += "";
            }
        }
        return ret;
    }
};

你可能感兴趣的:(IT公司面试习题)