題目地址: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.app
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.ide
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.code
Note:orm
words
has length in range [0, 50]
.words[i]
has length in range [1, 10]
.S
has length in range [0, 500]
.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"
會使用更多的標籤,所以是錯誤的。leetcode
先使用一個數組isBold保存S中的每一個字符是否應該加粗,判斷的方式是,遍歷words中的每一個字符串,找出S中有哪些位置和它匹配。字符串
是否增長標籤<b>
的方法是當前字符須要加粗,可是其前面的字符不用加粗,或者當前字符是第一個字符。
是否增長標籤</b>
的方法是當前字符須要加粗,可是其後面的字符不用加粗,或者當前字符是最後一個字符。string
C++代碼以下:it
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 日 —— 今日又是九一八io