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.html
Example 1:java
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:app
这道题给咱们了一个字符串,还有一个字典,让咱们把字符串中在字典中的单词加粗,注意若是两个单词有交集或者相接,就放到同一个加粗标签中。博主刚开始的想法是,既然须要匹配字符串,那么就上KMP大法,而后获得每一个单词在字符串匹配的区间位置,而后再合并区间,再在合并后的区间两头加标签。可是一看题目难度,Medium,中等难度的题不至于要祭出KMP大法吧,因而去网上扫了一眼众神们的解法,发现大多都是暴力匹配啊,既然OJ能过去,那么就一块儿暴力吧。这题参考的是高神shawngao的解法,高神但是集了一千五百多个赞的男人,叼到飞起!思路是建一个和字符串s等长的bold布尔型数组,表示若是该字符在单词里面就为true,那么最后咱们就能够根据bold数组的真假值来添加标签了。咱们遍历字符串s中的每个字符,把遍历到的每个字符看成起始位置,咱们都匹配一遍字典中的全部单词,若是能匹配上,咱们就用i + len来更新end,len是当前单词的长度,end表示字典中的单词在字符串s中结束的位置,那么若是i小于end,bold[i]就要赋值为true了。最后咱们更新完bold数组了,就再遍历一遍字符串s,若是bold[i]为false,直接将s[i]加入结果res中;若是bold[i]为true,那么咱们用while循环来找出全部连续为true的个数,而后在左右两端加上标签,参见代码以下:post
解法一:ui
class Solution { public: string addBoldTag(string s, vector<string>& dict) { string res = ""; int n = s.size(), end = 0; vector<bool> bold(n, false); for (int i = 0; i < n; ++i) { for (string word : dict) { int len = word.size(); if (i + len <= n && s.substr(i, len) == word) { end = max(end, i + len); } } bold[i] = end > i; } for (int i = 0; i < n; ++i) { if (!bold[i]) { res.push_back(s[i]); continue; } int j = i; while (j < n && bold[j]) ++j; res += "<b>" + s.substr(i, j - i) + "</b>"; i = j - 1; } return res; } };
这道题跟以后的那道Bold Words in String是如出一辙的题,那么解法固然是能够互通的了,这里咱们把那道题中解法二也贴过来吧,因为解法一和解法二实在是太类似了,就贴一个吧,具体讲解能够参见Bold Words in String这篇帖子,参见代码以下:url
解法二:spa
class Solution { public: string addBoldTag(string s, vector<string>& dict) { string res = ""; int n = s.size(); unordered_set<int> bold; for (string word : dict) { int len = word.size(); for (int i = 0; i <= n - len; ++i) { if (s[i] == word[0] && s.substr(i, len) == word) { for (int j = i; j < i + len; ++j) bold.insert(j); } } } for (int i = 0; i < n; ++i) { if (bold.count(i) && !bold.count(i - 1)) res += "<b>"; res += s[i]; if (bold.count(i) && !bold.count(i + 1)) res += "</b>"; } return res; } };
相似题目:code
参考资料:
https://discuss.leetcode.com/topic/92112/java-solution-boolean-array