【LeetCode】616. Add Bold Tag in String

来源:互联网 发布:c 并行编程 编辑:程序博客网 时间:2024/06/05 17:09

【LeetCode】616. Add Bold Tag in String


【题目描述】

  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.

  Note:

  1. The given dict won't contain duplicates, and its length won't exceed 100.
  2. All the strings in input have length in range [1, 1000].


【输入输出】

  Input 1: s="abcxyz123", dict=["abc", "123"]  =>  <b>abc</b>xyz<b>123</b>

  Input 2: s="aaabbcc", dict=["aaa", "aab", "bc"]  => <b>aaabbc</b>c


【解题思路】

  1. colored数组记录s中是否包含dict中字符串,若包含,将对应位置为'1',否则为'0'

  2. 使用KMP字符串匹配算法找出s中包含的dict中字符串的所有位置,将对应colored置为'1'

  3. 将colored中连续1用<b></b>包围


【代码】

class Solution {vector<vector<int>> next;string colored = "";void getNext(vector<string>& dict) {int dlen = dict.size();next.resize(dlen);for (int i = 0; i < dlen; i++) {next[i].resize(dict[i].length());next[i][0] = -1;for (int j = 0; j < dict[i].length() - 1; j++) {int k = next[i][j];while (k != -1 && dict[i][j] != dict[i][k]) k = next[i][k];next[i][j+1] = k + 1;}}}void kmp(string s, string t, int index) {int i = 0, j = 0;while (i < s.length()) {if (j == -1 || s[i] == t[j]) {i++, j++;if (j == t.length()) {while (j != 0) colored[i - j--] = '1';i -= (t.length() - 1);}}else j = next[index][j];}}public:string addBoldTag(string s, vector<string>& dict) {int slen = s.length(), dlen = dict.size();next.resize(dlen);getNext(dict);for (int i = 0; i < slen; i++) colored += "0";for (int i = 0; i < dlen; i++) kmp(s, dict[i], i);string ans = (colored[0] == '1') ? "<b>" : "";for (int i = 0; i < slen; i++) {ans += s[i];if (colored[i] == '1' && (colored[i + 1] == '0' || colored[i + 1] == '\0')) ans += "</b>";else if (colored[i] == '0' && colored[i + 1] == '1') ans += "<b>";}return ans;}};  // 32ms



原创粉丝点击