EngTW / English-for-Programmers

《程式英文》:用英文提昇程式可讀性
971 stars 45 forks source link

771. Jewels and Stones #75

Closed twy30 closed 3 years ago

twy30 commented 3 years ago

https://leetcode.com/problems/jewels-and-stones/

using System.Linq;

public class Solution
{
    public int NumJewelsInStones(string J, string S)
    {
        // 「寶石」(複數)
        var jewels = J;

        // 「石頭」(複數)
        var stones = S;

        // 「寶石的集合」
        var jewelSet = jewels.ToHashSet();

        return stones
        .Where(stone => jewelSet.Contains(stone))
        .Count();
    }
}

請參考「刷 LeetCode 練習命名」 https://github.com/EngTW/English-for-Programmers/issues/69 😊

LPenny-github commented 3 years ago

再麻煩 @twy30 給予命名建議 orz 非常感謝 orz

(本來是因為大大上一題 https://github.com/EngTW/English-for-Programmers/issues/74#issue-735004974 的答案所以試著用 Dictionary,結果看到大家的答案覺得自己頗丟臉 XDDDD 我會努力學習 orz)

public class Solution {
    public int NumJewelsInStones(string jewels, string stones) {

        // 把 stones 做成字典
        var stonesCategoryCount = new Dictionary<char, int>();

        foreach (var i in stones)
        {
            if (stonesCategoryCount.ContainsKey(i))
            {
                ++stonesCategoryCount[i];
            }
            else
            {
                stonesCategoryCount[i] = 1;
            }
        }

        // 如果 jewels[i] == 字典裡的索引,那就加總該索引的值
        int jewelsInStonesCount= 0;

        for(int i = 0; i < jewels.Length; ++i)
        {
            if(stonesCategoryCount.ContainsKey(jewels[i]))
            {
                jewelsInStonesCount += stonesCategoryCount[jewels[i]];
            }
        }

        return jewelsInStonesCount;
    }
}
twy30 commented 3 years ago

@LPenny-github

每個人都是從零開始學起的 😊


        var stonesCategoryCount = new Dictionary<char, int>();

        int jewelsInStonesCount= 0;
LPenny-github commented 3 years ago

@twy30

這裡或許用 stoneCounts 「石頭 (的) 數量 (複數)」 會更適合 🤔 這裡也可以寫成 jewelCount 「寶石 (的) 數量」

我想大大應該內建想法是 「石頭 種類 (的) 數量 (複數)」和 「寶石 種類 (的) 數量」🤔,所以前者是複數,後者是單數?


另外,我也發現:

例如,假設我們要說「書 (的) 標題」,會寫成 bookTitle, 而非 booksTitle

我以為疊字是 N (stones) + V (count) 這樣疊,但其實是 N (stone)+ N (counts)


感謝大大 orz

twy30 commented 3 years ago

這裡或許用 stoneCounts 「石頭 (的) 數量 (複數)」 會更適合 🤔 這裡也可以寫成 jewelCount 「寶石 (的) 數量」

我想大大應該內建想法是 「石頭 種類 (的) 數量 (複數)」和 「寶石 種類 (的) 數量」🤔,所以前者是複數,後者是單數?

我對前者的想法是:

我對後者的想法是:


另外,我也發現:

例如,假設我們要說「書 (的) 標題」,會寫成 bookTitle, 而非 booksTitle

我以為疊字是 N (stones) + V (count) 這樣疊,但其實是 N (stone)+ N (counts)

這裡有兩個面向:「美式英文文法」與「寫程式會用到的英文」。

從英文文法「用單字組成新的字/片語」的角度來看,可以參考這兩篇:

從「程式英文」的角度來看,我們是要命名「這個變數/類別是代表『什麼樣的東西』」;而『什麼樣的東西』就分成「描述『什麼樣』的形容詞」與真正的「東西」本體。

這裡的 stoneCounts 是「一種或以上『石頭的數量』」,的確是名詞「石頭」形容名司「數量」。