【Leetcode】800. Similar RGB Color
題目地址:
https://leetcode.com/problems/similar-rgb-color/
給定一個顏色的十六進位制編號,再定義兩個顏色的相似度, # A B C D E F \#ABCDEF #ABCDEF和 # U V W X Y Z \#UVWXYZ #UVWXYZ的相似度是 − ( A B − U V ) 2 − ( C D − W X ) 2 − ( E F − Y Z ) 2 -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2 −(AB−UV)2−(CD−WX)2−(EF−YZ)2,其中的 A B , U V AB,UV AB,UV等等要看成某個數的十六進位制表示。給定某個顏色 # A B C D E F \#ABCDEF #ABCDEF,要求找到與其相似度最高的,並且形如 # U U W W Y Y \#UUWWYY #UUWWYY的顏色。
程式碼如下:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public String similarRGB(String color) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i <= 9; i++) {
map.put((char) ('0' + i), i);
}
for (char i = 'a'; i <= 'f'; i++) {
map.put(i, i - 'a' + 10);
}
StringBuilder sb = new StringBuilder();
sb.append('#');
for (int i = 1; i < color.length(); i += 2) {
int cur = parseHex(color.substring(i, i + 2), map);
for (int j = 0; cur - j >= 0 && cur + j <= 272; j++) {
String n1 = Integer.toHexString(cur + j), n2 = Integer.toHexString(cur - j);
// 長度不足2要補齊
if (n1.length() < 2) {
n1 = "0" + n1;
}
if (n2.length() < 2) {
n2 = "0" + n2;
}
// 看一下是否形如AA
if (n1.charAt(0) == n1.charAt(1)) {
sb.append(n1);
break;
}
if (n2.charAt(0) == n2.charAt(1)) {
sb.append(n2);
break;
}
}
}
return sb.toString();
}
private int parseHex(String s, Map<Character, Integer> map) {
return map.get(s.charAt(0)) * 16 + map.get(s.charAt(1));
}
}
時空複雜度 O ( 1 ) O(1) O(1)。
相關文章
- 【AGC025B】RGB ColorGC
- LeetCode之Leaf-Similar Trees(Kotlin)LeetCodeMILAKotlin
- How to create the Gold gold using RGB color values All In OneGo
- [LeetCode] 1750. Minimum Length of String After Deleting Similar EndsLeetCodeMILA
- Leetcode PHP題解--D45 D45 872. Leaf-Similar TreesLeetCodePHPMILA
- AtCoder Beginner Contest 282 G - Similar PermutationMILA
- Color infection
- putty color
- RGB2YUV 的verilog實現(RGB轉YUV)
- found an invalid color
- Color Rows and Columns
- SCSS Color 型別CSS型別
- How to change the background color for PyCharmPyCharm
- CSS text-fill-colorCSS
- Flutter之Color物件(譯)Flutter物件
- F. Color Rows and Columns
- 使用uview元件報錯border-color: $u-border-color!important報錯View元件Import
- RGB與YIQ的轉換
- css11 CSS RGB ColorsCSS
- HTML input color 拾色器HTML
- ng-color-picker的使用
- AndroidStudio3.3以上color取色Android
- YUV <——> RGB 轉換演算法演算法
- h5 canvas 顯示rgbH5Canvas
- Photoshop 中的 Liquid Chrome RGB DropletsUIChrome
- text-decoration與color屬性
- CSS 字型新玩法之 Color FontCSS
- CSS3 text-fill-colorCSSS3
- color-關於顏色值
- Color Wheel for Mac (數字色輪)Mac
- Color Wheel for Mac數字色輪Mac
- 筆記-YUV和RGB的那些事~筆記
- -RGB畫素值分解的含義-
- Linux下無法執行Color pickerLinux
- CSS-背景顏色|background-colorCSS
- react-color庫的簡單使用React
- CSS color-scheme 和夜間模式CSSScheme模式
- Android Color 判斷色值小結Android