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 length 7.
  • color is a valid RGB color: for i > 0color[i] is a hexadecimal digit from 0 to f
  • 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.

大写字母组成的16进制字符串表示RGB颜色,可以简写为'#XYZ'形式的,两个颜色的相似度由给的公式计算得出。给一个颜色,求和它最相似的颜色,返回的是7个字符表示的颜色。

解法1:暴力brute force.

解法2:取余取模

解法3: 将字符串分为3个部分,对每个部分找个最相近的 ‘XX’ 格式的值即可。对于每一个 ‘XY’ 值,最近的一定在 ‘XX’, ‘(X-1)(X-1)’, ‘(X+1)(X+1)’ 之中,所以计算出这三个值取最近的即可。

Java:  暴力

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(16) for j in range(16) for k in range(16)]
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>d:
min=d
res=s
return '#'+''.join(res)
 

Python: 暴力

class Solution(object):
def similarRGB(self, color):
"""
:type color: str
:rtype: str
"""
ir, ig, ib = (int(color[x: x+2], 16)
for x in (1, 3, 5))
ans = ()
delta = 0x7FFFFFFF
for r in range(16):
for g in range(16):
for b in range(16):
ndelta = sum((ic - c * 17) ** 2
for ic, 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: 解法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, 16), 17)
if r > 8: q += 1
return '{:02x}'.format(17*q) return '#' + \
rounding(color[1:3]) + \
rounding(color[3:5]) + \
rounding(color[5:7])  

Python:  解法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)*2 if c<=9 else chr(c-10+ord('a'))*2
return ret  

C++: 暴力,T: O(3 * 16)  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]) * 16 + 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 < 16; ++j) {
int diff = abs(j * 16 + 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, 16);
int idx = num / 17 + (num % 17 > 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, 16);
int idx = num / 17 + (num % 17 > 8 ? 1 : 0);
color[i] = color[i + 1] = (idx > 9) ? (idx - 10 + 'a') : (idx + '0');
}
return color;
}
};

  

 

All LeetCode Questions List 题目汇总

[LeetCode] 800. Similar RGB Color 相似的红绿蓝颜色的更多相关文章

  1. [LeetCode] Similar RGB Color 相似的红绿蓝颜色

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

  2. 【LeetCode】800. Similar RGB Color 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...

  3. FPGA驱动LCD显示红绿蓝彩条

    实验目的:先简单熟悉LCD灯的驱动和时序图的代码实现.设计功能是让LCD显示红绿蓝三种颜色,即三个彩带.本次实验比较容易实现,主要是对LCD驱动时序图的理解和时序参数的配置. 实验条件:1.LCD原理 ...

  4. 阶段小项目1:循环间隔1秒lcd显示红绿蓝

    #include<stdlib.h>#include<stdio.h>#include<string.h>#include<error.h>#inclu ...

  5. Hierarchical clustering:利用层次聚类算法来把100张图片自动分成红绿蓝三种色调—Jaosn niu

    #!/usr/bin/python # coding:utf-8 from PIL import Image, ImageDraw from HierarchicalClustering import ...

  6. C#Color对象的使用介绍及颜色对照表

    原文地址  http://blog.sina.com.cn/s/blog_3e1177090101bzs3.html 今天用到了特转载 NET框架中的颜色基于4种成份,透明度,红,绿和蓝.每一种成份都 ...

  7. RGB Color Codes Chart

    RGB Color Codes Chart RGB颜色空间 RGB颜色空间或RGB颜色系统,从红色.绿色和蓝色的组合中构造所有颜色. 红色.绿色和蓝色各使用8位,它们的整数值从0到255.这使得256 ...

  8. 【AGC025B】RGB Color

    [AGC025B]RGB Color 题面描述 Link to Atcoder Link to Luogu Takahashi has a tower which is divided into \( ...

  9. (转)如何根据RGB值来判断这是种什么颜色?

    如何根据RGB值来判断这是种什么颜色? 下面介绍几种典型颜色的RGB值,格式为:颜色(R,G,B). 想象一下有红.绿.蓝三盏射灯打出三束光. 这三束光叠加在一起时产生白色,如果三盏灯的亮度都减半就产 ...

随机推荐

  1. The Shortest Statement(Educational Codeforces Round 51 (Rated for Div.2)+最短路+LCA+最小生成树)

    题目链接 传送门 题面 题意 给你一张有\(n\)个点\(m\)条边的联通图(其中\(m\leq n+20)\),\(q\)次查询,每次询问\(u\)与\(v\)之间的最短路. 思路 由于边数最多只比 ...

  2. Spring Boot-初学01 -使用Spring Initializer快速创建Spring Boot项目 -@RestController+spEL -实现简单SpringBoot的Web页面

    1.IDEA:使用 Spring Initializer快速创建项目 IDE都支持使用Spring的项目创建向导快速创建一个Spring Boot项目: 选择我们需要的模块:向导会联网创建Spring ...

  3. linux Crontab定时备份项目案例

    首先先写好备份的脚本(拷贝的命令) #bash/bin cd /finance/tomcat8-finance/wtpwebapps tar -czf /finance/webapp_backup/* ...

  4. webpack脚手架增加版本号

    1.product模式下,新增版本号: 1)common.js文件中,输出的文件路径要跟着变化 output: { filename: 'js/[name].js', path: path.resol ...

  5. 记录一次编译安装Pg_rman缺少依赖包的问题

    系统版本:CentOS版本6.10(最终版) pg_rman:https://github.com/ossc-db/pg_rman -bash-4.1$ makegcc -Wall -Wmissing ...

  6. Xms Xmx PermSize MaxPermSize的含义

    参数的含义 -vmargs -Xms128M -Xmx512M -XX:PermSize=64M -XX:MaxPermSize=128M -vmargs 说明后面是VM的参数,所以后面的其实都是JV ...

  7. python的readline() 和readlines()

    .readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样..readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python ...

  8. [转贴] bu AU3脚本录制工具(软件自动化安装的最简便的方法)

    http://www.autoitx.com/thread-15419-1-1.html 1,打开一个.au3的文档或者新建一个.au3的文档,用SciTE编辑; 2,按下ALT+F6,弹出下面的对话 ...

  9. 开源项目 03 DocX

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  10. 【JZOJ6228】【20190621】ni

    题目 $ n $ 个数 $ E_i $ ,$ F(i) $ 表示对1-i的数任意排列 $ p $ ,初始 $ X=0 $ ,依次执行: \(X \lt E_{p_j} \ , \ X++\) $X \ ...