[Leetcode] 800. Similar RGB color similar to red-green-blue

Source: Internet
Author: User

In the following, every capital letter represents some hexadecimal digit from 0 to f .

The Red-green-blue color "#AABBCC" can written as in "#ABC" shorthand. For example, was shorthand for the "#15c" color "#1155cc" .

Now, say the similarity between-colors and is "#ABCDEF" "#UVWXYZ" -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2 .

Given the color "#ABCDEF" , return a 7 character color that's most similar #ABCDEF to, and have a shorthand (that's, it can be r Epresented 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:

    • coloris a string of length 7 .
    • coloris a valid RGB color:for i > 0 , was color[i] a hexadecimal digit from 0 tof
    • Any answer which have the same (highest) similarity as the best answer would be accepted.
    • All inputs and outputs should use lowercase letters, and the output is 7 characters.

A 16 binary string consisting of uppercase letters represents the RGB color, which can be abbreviated as ' #XYZ ', and the similarity of two colors is calculated by the formula given. Give a color, sum it the most similar color, and return the color represented by 7 characters.

Solution 1: Violence brute force.

Solution 2:

Solution 3: Divide the string into 3 parts and find the nearest ' XX ' format value for each section. For each ' XY ' value, the nearest must be in ' XX ', ' (X-1) (X-1) ', ' (x+1) ' (x+1) ', so calculate these three values to take the nearest one.

Java: Violence

Class Solution:    def similarrgb (self, color): "" "        : Type color:str        : Rtype:str        " ""        r,g,b = Int ( color[1:3],16), int (color[3:5],16), int (color[5:7],16)        a = [' 00 ', ' 11 ', ' 22 ', ' 33 ', ' 44 ', ' 55 ', ' 66 ', ' 77 ', ' 88 ', ' 99 ', ' AA ', ' BB ', ' cc ', ' dd ', ' ee ', ' ff ']        p = [(A[i],a[j],a[k]) for I in range (+) for J in range (+) for K in range (+)]        res , Min = ", 9999999 for        s in P:            d = (int (s[0],16)-R) **2 + (int (s[1],16)-G) **2 + (int (s[2],16)-B) **2            if MIN&G T;d:                min=d                res=s        return ' # ' + '. Join (RES)    

Python: Violence

Class solution (Object):    def similarrgb (self, color): "" "        : Type color:str        : Rtype:str        "        "" IR , IG, IB = (int (color[x:x+2], +) for                      x in (1, 3, 5))        ans = ()        delta = 0x7FFFFFFF for        R in range: 
   for g in range (+):                for B in range (+):                    Ndelta = SUM ((IC-C *) * * 2                                 for ICS, C in Zip (IR, IG, IB), (R , G, B)))                    if Ndelta < delta:                        delta = ndelta                        ans = r, G, b        return ' # ' + '. Join (Hex (c) [2] * 2 for C In ans)

Python: Solution 2 Time:o (1), Space:o (1)

Class solution (Object):    def similarrgb (self, color): "" "        : Type color:str        : Rtype:str        "        "" Def rounding (color):            q, r = divmod (int (color, +), +)            if r > 8:q + = 1            return ' {: 02x} '. Format (17*q)        re Turn ' # ' +                 rounding (Color[1:3]) +                 rounding (Color[3:5]) +                 rounding (Color[5:7])

Python: Solution 3

def similarrgb (self, color):    ret = ' # ' for    I in range (1, 6, 2):        c1, c2 = [Int (_) if ' 0 ' <=_<= ' 9 ' else 10+ord (_)-ord (' a ') for _ in color[i:i+2]]        c = c1+sorted (Enumerate ([ABS ((C1*16+C2)-(x*16+x)) for x in [C1-1, C1, c1+1] ]), Key=lambda _:_[1]) [0][0]-1        ret + = str (c) * If c<=9 else Chr (C-10+ord (' a ')) * *    return RET

C + +: Violence, T:o (3 *) S:o (1)

Class Solution {public:  string Similarrgb (string color) {    const string hex{"0123456789abcdef"};    Vector<int> RGB (3, 0);    for (int i = 0; i < 3; ++i)      rgb[i] = hex.find (color[2 * i + 1]) * + hex.find (color[2 * i + 2]);        String ans (7, ' # ');        for (int i = 0; i < 3; ++i) {      int. best = Int_max;      for (int j = 0; J < ++j) {        int diff = ABS (J * + j-rgb[i]);        if (diff >= Best) continue;        Best = diff;        ans[2 * i + 1] = ans[2 * i + 2] = Hex[j];      }    }    return ans;  };

C++:

Class Solution {public:    string Similarrgb (string color) {        return "#" + Helper (Color.substr (1, 2)) + helper (color. SUBSTR (3, 2) + Helper (Color.substr (5, 2));    }    String Helper (String str) {        string dict = "0123456789abcdef";        int num = Stoi (str, nullptr, +);        int idx = NUM/17 + (num% > 8? 1:0);        return string (2, Dict[idx]);}    ;

C++:

Class Solution {public:    string Similarrgb (string color) {for        (int i = 1; i < color.size (); i + = 2) {            int num = Stoi (Color.substr (i, 2), nullptr, +);            int idx = NUM/17 + (num% > 8? 1:0);            Color[i] = color[i + 1] = (idx > 9)? (idx-10 + ' A '): (idx + ' 0 ');        }        return color;    }};

  

 

[Leetcode] 800. Similar RGB color similar to red-green-blue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.