3208. Alternating Groups II
- 
Extend the Array: To handle the circular nature of the array, extend the colorsarray by appending the firstk-1elements to its end. This allows us to easily check for alternating groups that wrap around the end of the array.
- 
Initialize Counters: - resto store the number of alternating groups.
- cntto count the length of the current alternating group.
 
- 
Iterate Through the Extended Array: - For each tile, check if its color is different from the previous tile.
- If it is, increment the cntcounter.
- If it isn't, reset the cntcounter to 1.
- If the cntcounter reachesk, increment therescounter as it indicates the end of an alternating group.
 
- 
Return the Result: Finally, return the rescounter, which represents the number of alternating groups of lengthk.
class Solution {
public:
    int numberOfAlternatingGroups(vector<int>& colors, int k)
    {
        for (int i = 0; i < k - 1; ++i)
        {
            colors.push_back(colors[i]);
        }
        int res = 0;
        // cnt 用來記錄長度是否達到 k
        int cnt = 1;
        for (int i = 1; i < colors.size(); ++i)
        {
            // 如果是交錯的格子,則 cnt++
            if (colors[i] != colors[i - 1])
            {
                ++cnt;
            }
            else
            {
                // 如果不是交錯的格子,則 reset cnt= 1
                cnt = 1;
            }
            // 如果 cnt 達到 k,則結果 + 1
            if (cnt >= k) ++res;
        }
        return res;
    }
};
- T:
- S: