- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 85 lines of C++ from the credited upstream file 411.cpp.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string minAbbreviation(string target, vector<string>& dictionary) {4 const int m = target.length();5 vector<int> masks;6 7 for (const string& word : dictionary) {8 if (word.length() != m)9 continue;10 masks.push_back(getMask(target, word));11 }12 13 if (masks.empty())14 return to_string(m);15 16 vector<string> abbrs;17 18 const int maxCand = pow(2, m);19 20 for (int cand = 0; cand < maxCand; ++cand)21 22 if (ranges::all_of(masks, [cand](int mask) { return cand & mask; }))23 abbrs.push_back(getAbbr(target, cand));24 25 string ans = target;26 27 for (const string& abbr : abbrs)28 if (getAbbrLen(abbr) < getAbbrLen(ans))29 ans = abbr;30 31 return ans;32 }33 34 private:35 int getMask(const string& target, const string& word) {36 const int m = target.length();37 38 39 40 41 42 int mask = 0;43 for (int i = 0; i < m; ++i)44 if (word[i] != target[i])45 mask |= 1 << m - 1 - i;46 return mask;47 }48 49 string getAbbr(const string& target, int cand) {50 const int m = target.length();51 string abbr;52 int replacedCount = 0;53 for (int i = 0; i < m; ++i)54 if (cand >> m - 1 - i & 1) {55 56 if (replacedCount > 0)57 abbr += to_string(replacedCount);58 abbr += target[i];59 replacedCount = 0;60 } else {61 62 ++replacedCount;63 }64 if (replacedCount > 0)65 abbr += to_string(replacedCount);66 return abbr;67 }68 69 int getAbbrLen(const string& abbr) {70 int abbrLen = 0;71 int i = 0;72 int j = 0;73 while (i < abbr.length()) {74 if (isalpha(abbr[j]))75 ++j;76 else77 while (j < abbr.length() && isdigit(abbr[j]))78 ++j;79 ++abbrLen;80 i = j;81 }82 return abbrLen;83 }84};85