EngTW / English-for-Programmers

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

1640. Check Array Formation Through Concatenation #85

Closed twy30 closed 3 years ago

twy30 commented 3 years ago

https://leetcode.com/problems/check-array-formation-through-concatenation/

using System.Collections.Generic;

public class Solution
{
    public bool CanFormArray(int[] arr, int[][] pieces)
    {
        // 「輸入的數字」(複數)
        var inputNumbers = arr;

        // 「『輸入的數字』的索引值」
        var inputNumberIndexes = new Dictionary<int, int>();

        for (int i = 0; i < inputNumbers.Length; i++)
        {
            inputNumberIndexes.Add(inputNumbers[i], i);
        }

        foreach (var piece in pieces)
        {
            // 「 piece 起始索引值」
            int pieceStartIndex;
            if (inputNumberIndexes.TryGetValue(piece[0], out pieceStartIndex))
            {
                for (int i = 0; i < piece.Length; ++i)
                {
                    // 「『比對』索引值」
                    var comparisonIndex = pieceStartIndex + i;

                    if (comparisonIndex >= inputNumbers.Length) { return false; }

                    if (piece[i] != inputNumbers[comparisonIndex]) { return false; }
                }
            }
            else
            {
                return false;
            }
        }

        return true;
    }
}

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

twy30 commented 3 years ago

這裡遇到個很有趣的情形

            // 「 piece 在 InputNumbers 中的起始索引值」, "piece" 取自 LeetCode 題目敘述用字
            var pieceStartIndexInInputNumbers = inputNumberIndexes[piece[0]];

pieceStartIndexInInputNumbers 由 6 個英文字組成,雖然在英文語法、語意上算是清楚,但不易閱讀。

或許這裡應該採用折衷的做法 🤔 例如:

twy30 commented 3 years ago

更新 LeetCode 解答,採用「變數名稱縮為 pieceStartIndex」。