题目地址:https://leetcode-cn.com/problems/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 <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.

题目大意

给定一个关键词集合 words 和一个字符串 S,将所有 S 中出现的关键词加粗。所有在标签 <b></b> 中的字母都会加粗。
返回的字符串需要使用尽可能少的标签,当然标签应形成有效的组合。
例如,给定 words = ["ab", "bc"]S = "aabcd",需要返回 "a<b>abc</b>d"。注意返回 "a<b>a<b>b</b>c</b>d" 会使用更多的标签,因此是错误的。

解题方法

遍历

先使用一个数组isBold保存S中的每个字符是否应该加粗,判断的方式是,遍历words中的每个字符串,找出S中有哪些位置和它匹配。

是否增加标签<b>的方法是当前字符需要加粗,但是其前面的字符不用加粗,或者当前字符是第一个字符。
是否增加标签</b>的方法是当前字符需要加粗,但是其后面的字符不用加粗,或者当前字符是最后一个字符。

C++代码如下:

class Solution {
public:
string boldWords(vector<string>& words, string S) {
const int N = S.size();
vector<bool> isBold(N, false);
for (string& word : words) {
for (int i = 0; i < N; ++i) {
string sub = S.substr(i, word.size());
if (sub == word) {
for (int k = i; k < i + word.size(); ++k) {
isBold[k] = true;
}
}
}
}
string res;
for (int i = 0; i < N; ++i) {
if (isBold[i] && (i == 0 || !isBold[i - 1])) {
res += "<b>";
}
res += S[i];
if (isBold[i] && (i == N - 1 || !isBold[i + 1])) {
res += "</b>";
}
}
return res;
}
};

日期

2019 年 9 月 18 日 —— 今日又是九一八

最新文章

  1. android中如何用代码来关闭打开的相机
  2. [转]C#在创建完项目后如何重命名项目名称。
  3. MVC利用URLRoute实现伪静态
  4. gulp学习笔记4
  5. 仿照jquery封装一个自己的js库(二)
  6. java事务的处理
  7. System.Runtime.InteropServices.COMException (0x800706BA) 解决方法
  8. bzoj3632
  9. /boot/grub/menu.lst详解
  10. 深入解析Java对象的hashCode和hashCode在HashMap的底层数据结构的应用
  11. 数据结果与算法分析(1)&mdash;&mdash;算法分析
  12. 问题:loadrunner录制event为0
  13. java 正则表达式去除标点符号
  14. 初识lucene
  15. make deb for debian/ubuntu, package software for debian/ubuntu
  16. SQL查询--选择运算(1)
  17. TypeError:_12.store.query is not a function
  18. 常用的消息队列中间件mq对比
  19. recovery 升级界面顶部花屏问题分析
  20. Nginx禁止直接通过IP地址访问网站以及限制IP登陆某目录(关闭默认站点或空主机头)

热门文章

  1. python12类
  2. 苹果ios通过描述文件获取udid
  3. ubuntu安装配置ssh-connect to host localhost port 22: Connection refused
  4. 求解线性递推方程第n项的一般方法
  5. day15 内置函数和模块
  6. 最长公共子序列问题(LCS) 洛谷 P1439
  7. awk的基本用法
  8. [项目总结]怎么获取TextView行数,为什么TextView获取行数为0?
  9. EBS 抓trace 文件
  10. OpenStack之六: plancement服务(端口8778)