In the following, every capital letter represents some hexadecimal digit from
0
to f
.
The red-green-blue color
"#AABBCC"
can be written as "#ABC"
in shorthand. For example, "#15c"
is shorthand for the color "#1155cc"
.
Now, say the similarity between two colors
"#ABCDEF"
and "#UVWXYZ"
is -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2
.
Given the color
"#ABCDEF"
, return a 7 character color that is most similar to #ABCDEF
, and has a shorthand (that is, it can be represented as some "#XYZ"
Example 1: Input: color = "#09f166" Output: "#11ee66" Explanation: The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73. This is the highest among any shorthand color.
Note:
color
is a string of length7
.color
is a valid RGB color: fori > 0
,color[i]
is a hexadecimal digit from0
tof
- Any answer which has the same (highest) similarity as the best answer will be accepted.
- All inputs and outputs should use lowercase letters, and the output is 7 characters.
Solution #1
class Solution { private static int[] preset = {0,17,34,51,68,85,102,119,136,153,170,187,204,221,238,255}; private static String[] hex = {"00","11","22","33","44","55","66","77","88","99","aa","bb","cc","dd","ee","ff"}; public String similarRGB(String color) { String s = "#"; for (int i = 1; i < color.length(); i += 2) { int min = 0; int cand = toInt(color.charAt(i)) * 16 + toInt(color.charAt(i + 1)); for (int j = 0; j < preset.length; j++) { if (Math.abs(cand - preset[j]) < Math.abs(cand - preset[min])) { min = j; } } s += hex[min]; } return s; } private int toInt(char c) { int rt = 0; if (Character.isDigit(c)) { rt = c - '0'; }else { rt = 10 + (c - 'a'); } return rt; } }
Solution #2: https://leetcode.com/problems/similar-rgb-color/discuss/119844/Concise-java-solution
No comments:
Post a Comment