[LeetCode] Similar RGB Color 類似的紅綠藍顏色

 

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

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

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

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:spa

  • 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.

 

這道題定義了一種表示顏色的十六進制字符串,而後說是有一種兩兩字符相等的顏色能夠縮寫。而後又給了咱們一我的一的字符串,讓咱們找出距離其最近的能夠縮寫的顏色串。題意不難理解,並且仍是Easy標識符,因此咱們要有信心能夠將其拿下。那麼經過分析題目中給的例子, 咱們知道能夠將給定的字符串拆成三個部分,每一個部分分別來進行處理,好比對於字符串"#09f166"來講,咱們就分別處理"09","f1","66"便可。咱們的目標是要將每部分的兩個字符變爲相同,而且跟原來的距離最小,那麼實際上咱們並不須要遍歷全部的組合,由於比較有參考價值的就是十位上的數字,由於若是十位上的數字不變,或者只是增減1,而讓個位上的數字變更大一些,這樣距離會最小,由於個位上的數字權重最小。就拿"09"來舉例,這個數字能夠變成"11"或者"00",十六進制數"11"對應的十進制數是17,跟"09"相差了8,而十六進制數"00"對應的十進制數是0,跟"09"相差了9,顯然咱們選擇"11"會好一些。因此咱們的臨界點是"8",若是個位上的數字大於"8",那麼十位上的數就加1。code

下面來看如何肯定十位上的數字,好比拿"e1"來舉例,其十進制數爲225,其可能的選擇有"ff","ee",和"dd",其十進制數分別爲255,238,和221,咱們目測很容易看出來是跟"dd"離得最近,可是怎麼肯定十位上的數字呢。咱們發現"11","22","33","44"... 這些數字之間相差了一個"11",十進制數爲17,因此咱們只要將原十六進制數除以一個"11",就知道其能到達的位置,好比"e1"除以"11",就只能到達"d",那麼十進制上就是"d",至於個位數的處理狀況跟上面一段講解相同,咱們對"11"取餘,而後跟臨界點"8"比較,若是個位上的數字大於"8",那麼十位上的數就加1。這樣就能夠肯定正確的數字了,那麼組成正確的十六進制字符串便可,參見代碼以下:htm

 

解法一:blog

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]); } };

 

咱們也能夠不用helper函數,直接在一個函數中搞定便可,參見代碼以下:ci

 

解法二:leetcode

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; } };

 

參考資料:

https://leetcode.com/problems/similar-rgb-color/solution/

https://leetcode.com/problems/similar-rgb-color/discuss/120077/C++-Concise-Solution-with-explanation-6ms

https://leetcode.com/problems/similar-rgb-color/discuss/120093/C++-O(1)-time-and-space-Easy-to-Understand

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索