- 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
- 37 lines of C++ from the credited upstream file 800.cpp.
- The implementation visibly relies on sequence storage.
- 2 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 similarRGB(string color) {4 const vector<string> kShorthands = {"00", "11", "22", "33", "44", "55",5 "66", "77", "88", "99", "aa", "bb",6 "cc", "dd", "ee", "ff"};7 string ans = "#";8 9 for (int i = 1; i < color.length(); i += 2) {10 const int currValue = stoi(color.substr(i, 2), 0, 16);11 ans += findClosestShorthand(kShorthands, currValue);12 }13 14 return ans;15 }16 17 private:18 static constexpr int maxSimilarity = 255 * 255;19 20 string findClosestShorthand(const vector<string>& shorthands,21 int targetValue) {22 string closest = shorthands[0];23 int minSimilarity = maxSimilarity;24 25 for (const string& shorthand : shorthands) {26 const int shorthandValue = stoi(shorthand, 0, 16);27 const int similarity = pow((targetValue - shorthandValue), 2);28 if (similarity < minSimilarity) {29 closest = shorthand;30 minSimilarity = similarity;31 }32 }33 34 return closest;35 }36};37