- 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
- 34 lines of Java from the credited upstream file 800.java.
- 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 String similarRGB(String color) {3 String[] SHORTHANDS = {"00", "11", "22", "33", "44", "55", "66", "77",4 "88", "99", "aa", "bb", "cc", "dd", "ee", "ff"};5 StringBuilder ans = new StringBuilder("#");6 7 for (int i = 1; i < color.length(); i += 2) {8 final int currValue = Integer.parseInt(color.substring(i, i + 2), 16);9 String closestShorthand = findClosestShorthand(currValue, SHORTHANDS);10 ans.append(closestShorthand);11 }12 13 return ans.toString();14 }15 16 private static final int maxSimilarity = 255 * 255;17 18 private String findClosestShorthand(int targetValue, String[] shorthands) {19 String closest = shorthands[0];20 int minSimilarity = Integer.MAX_VALUE;21 22 for (final String shorthand : shorthands) {23 final int shorthandValue = Integer.parseInt(shorthand, 16);24 final int similarity = (targetValue - shorthandValue) * (targetValue - shorthandValue);25 if (similarity < minSimilarity) {26 closest = shorthand;27 minSimilarity = similarity;28 }29 }30 31 return closest;32 }33}34