Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. class Solution {
  2. public:
  3.         string addBoldTag(string s, vector<string>& dict) {
  4.         constexpr char const *kBoldOpenTag = "<b>";
  5.         constexpr char const *kBoldCloseTag = "</b>";
  6.  
  7.         vector<int> pattern_positions(s.size() + 1);
  8.  
  9.         for (auto& word : dict)
  10.           FindPatternStartEndPos(s, word, &pattern_positions);
  11.  
  12.         string wrapped_res = "";
  13.  
  14.         int curr_tags_balance = 0;
  15.         for (int i = 0; i < s.size(); ++i) {
  16.             if (pattern_positions[i] > 0) {
  17.                 if (curr_tags_balance == 0) wrapped_res += string(kBoldOpenTag);
  18.                 curr_tags_balance += pattern_positions[i];
  19.             }
  20.             else  if (pattern_positions[i] < 0) {
  21.                 curr_tags_balance += pattern_positions[i];
  22.                 if (curr_tags_balance == 0) wrapped_res += string(kBoldCloseTag);
  23.             }
  24.  
  25.             wrapped_res += s[i];
  26.         }
  27.         if (pattern_positions.back() < 0) wrapped_res += string(kBoldCloseTag);
  28.         return wrapped_res;
  29.     }
  30. private:
  31.     void FindPatternStartEndPos(const string& t, const string& p, vector<int>* pattern_positions) {
  32.         auto pi_function = CalculatePiFinction(t, p);
  33.  
  34.         for (int i = 0; i < pi_function.size(); ++i) {
  35.             if (pi_function[i] == p.size()) {
  36.                 pattern_positions->at(i - p.size() + 1) += 1;
  37.                 pattern_positions->at(i + 1) += -1;
  38.             }
  39.         }
  40.     }
  41.  
  42.     vector<int> CalculatePiFinction(const string& t, const string& p) {
  43.         const string kDelim{ "#" };
  44.         auto text = p + kDelim + t;
  45.         vector<int> pi_function(text.size());
  46.  
  47.         for (int i = 1; i < text.size(); ++i) {
  48.             int j = pi_function[i - 1];
  49.  
  50.             while (j && text[j] != text[i])
  51.                 j = pi_function[j - 1];
  52.  
  53.             if (text[i] == text[j]) pi_function[i] = j + 1;
  54.             // else - 0
  55.         }
  56.  
  57.         return vector<int>(pi_function.begin() + p.size() + kDelim.size(), pi_function.end());
  58.     }
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement