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.
Example 1:
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:
- The given dict won't contain duplicates, and its length won't exceed 100.
- All the strings in input have length in range [1, 1000].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | class Solution { bool isStartWith(string s, string w) { if(s.size()<w.size()) return false; return s.substr(0, w.size())==w; } public: string addBoldTag(string s, vector<string>& dict) { int n = s.size(); vector<bool> indicator(n, false);//true if the char should be put inside a bold pair for(int i=0, end = 0; i<n; ++i) { for(auto w:dict) { //s starts with w from i if(isStartWith(s.substr(i, s.size()-i), w)) { end = max(end, i+(int)w.size()); } } indicator[i] = (end>i);//end is the first char should not be put inside a bold pair } string ret; for(int i=0;i<n;) { int j=i; while(j<n && !indicator[j]) j++; ret.append(s.substr(i, j-i)); i=j; if(i==n) break; ret+="<b>"; while(j<n && indicator[j]) j++; ret.append(s.substr(i, j-i)); ret+="</b>"; i=j; } return ret; } }; |
No comments:
Post a Comment