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

本文介绍了一种算法,用于在给定的字符串中将特定关键词加粗显示,并确保使用最少的HTML标签完成这一任务。该算法通过扫描字符串并标记关键词出现的位置来实现,最终返回带有适当加粗标签的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b>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 "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" 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<string>& words, string S) {
        vector<bool> 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 += "<b>";
            }
            ret.push_back(S[i]);
            if ((i + 1 == S.length() && bolds[i]) || (i + 1 < S.length() && bolds[i] && !bolds[i + 1])) {
                ret += "</b>";
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值