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. 

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"
class Solution {
public:
    string addBoldTag(string s, vector<string>& dict) {
        vector<pair<int,int>> nums;
        for (string w : dict) {
            int n = w.size();
            for (int i = 0; (i = s.find(w, i)) != string::npos; i++) {
                nums.push_back({i, i + n});
            }
        }
        
        if (nums.size() == 0)
            return s;
        vector<pair<int,int>> intervals =  mergeIntervals(nums);
        
        for (auto it = intervals.rbegin(); it != intervals.rend(); it++) {
            s.insert(it->second, "</b>");
            s.insert(it->first, "<b>");
        }
        return s;
    }
private:
     vector<pair<int,int>> mergeIntervals(vector<pair<int,int>>&nums)
     {
          vector<pair<int,int>> res;
          if(nums.size()==0) return res;
          sort(nums.begin(),nums.end(),compare);
          res.push_back(nums[0]);
          for(int i = 1;i<nums.size();i++)
          {
             if(nums[i].first<=res.back().second)
                 res.back().second = max(res.back().second,nums[i].second);
             else
                 res.push_back(nums[i]);
          }
          return res;
     }
     static bool compare(pair<int,int>a,pair<int,int>b)
     {
         {return a.first==b.first?a.second<b.second:a.first<b.first;}
     }
    
    
};

 

posted @ 2017-11-23 17:02  jxr041100  阅读(207)  评论(0编辑  收藏  举报