LeetCode | 758. Bold Words in String 简单技巧题

Givena set of keywords words and a string S, make all appearances of allkeywords in S bold.Any letters between <b> and </b> tags become bold.

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

Forexample, given that words = ["ab", "bc"] and S ="aabcd", we shouldreturn "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it isincorrect.

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.

给你一个字符数组和一个字符串S,让你把S中所有字符数组中出现的字符都做重点标记,重点标记使用 <b> and </b> 来实现,这里要求使用的标记数量最少,

这题我花了一个小时都没想出来,因为我题目看不懂,make all appearances of all keywords in S bold这一句没看懂,后来再看一看,其实这一句就是把所有的S中的keywords都做重点标记,Any letters between <b> and </b> tags become bold是指怎样重点标记,看懂了这一句之后题目就变得非常的简单了,注意bold是重点标记的意思,也就是加粗的意思,

以后在做题的时候记得当题目看不懂的时候记得使用谷歌翻译,然后借鉴一下,这样说不定就看懂了

这一题还要注意一点,就是对于string.find_first_of(stringa)而言,返回的是a中的任何一个字符在string 中第一次出现的位置,而不是a在string中出现的第一次,要找a在string中出现的第一次请使用string.find()以后一定要注意!!!

class Solution {
public:
string boldWords(vector<string>& words, string S) {
	int start=0;

	vector<bool> mark(S.size(), false);

	for (int i = 0; i < words.size(); i++)
	{
		start= S.find(words[i], 0);
  		while (start != -1)
		{
			for (int j = start; j < start + words[i].size(); j++)
			{
				mark[j] = true;
			}
			start = S.find(words[i], start+1);
		}
	}
	int now = 0;
	string tmp = "";
	for (int i = 0; i < S.size(); i++)
	{
		if (mark[i] == true)
		{
			if (now == 0) { 
				tmp.insert(tmp.size(), "<b>"); now = 1; 
			}
			
		}
		else
		{
			if (now == 1) {
				tmp.insert(tmp.size(), "</b>"); now = 0;
			}
		}
		tmp.push_back(S[i]);
	}
	if (now == 1)
	{
		tmp.insert(tmp.size(), "</b>");
	}
	return tmp;
}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值