[Leetcode] 616. Add Bold Tag in String 解题报告

题目

Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two substrings wrapped by bold tags are consecutive, you need to combine them.

Example 1:

Input: 
s = "abcxyz123"
dict = ["abc","123"]
Output:
"<b>abc</b>xyz<b>123</b>"

Example 2:

Input: 
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"

Note:

  1. The given dict won't contain duplicates, and its length won't exceed 100.
  2. All the strings in input have length in range [1, 1000].

思路

很常规的思路:找出dict中的每个单词在s中的出现区段interval,然后将这些intervals进行merge,merge之后形成的不重合的intervals就是我们需要插入<b>或者</b>的地方。

当然本题目也可以用很牛逼的KMP算法实现,时间复杂度应该会更低。可是太难了,还是用简单的吧。

代码

class Solution {
public:
    string addBoldTag(string s, vector<string>& dict) {
        vector<pair<int, int>> ranges = findPairs(s, dict);
        ranges = merge(ranges);
        for (auto it = ranges.rbegin(); it != ranges.rend(); ++it) {
            s.insert(it->second, "</b>");
            s.insert(it->first, "<b>");
        }
        return s;
    }
private:
    vector<pair<int, int>> findPairs(string &s, vector<string> &dict) {
        vector<pair<int, int>> res;
        for (string w : dict) {
            int n = w.size();
            for (int i = 0; (i = s.find(w, i)) != string::npos; ++i) {
                res.push_back(pair<int, int>(i, i + n));
            }
        }
        return res;
    }
    vector<pair<int ,int>> merge(vector<pair<int, int>> &a) {
        vector<pair<int, int>> r;
        sort(a.begin(), a.end(), compare);
        for (int i = 0, j = -1; i < a.size(); ++i) {
            if (j < 0 || a[i].first > r[j].second) {
                r.push_back(a[i]);
                ++j;
            }
            else {
                r[j].second = max(r[j].second, a[i].second);
            }
        }
        return r;
    }
    static bool compare(pair<int, int> &a, pair<int, int> &b) {
        return a.first < b.first || a.first == b.first && a.second < b.second;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值