# Weekly Contest 396 日期 2024/05/05 第二跟第三題一直誤會題目意思,若能夠靜下心來寫,我想很快就能解出來。 - [Valid Word](https://leetcode.com/problems/valid-word/) - [Minimum Number of Operations to Make Word K-Periodic](https://leetcode.com/problems/minimum-number-of-operations-to-make-word-k-periodic/) - [Minimum Length of Anagram Concatenation](https://leetcode.com/problems/minimum-length-of-anagram-concatenation/) - [Minimum Cost to Equalize Array](https://leetcode.com/problems/minimum-cost-to-equalize-array/) ### 第一題 ```clike class Solution { public: bool isValid(string word) { const int n = word.size(); if(n < 3) return false; bool vowel = false; bool consonant = false; for(char x: word) { bool la = 'a' <= x && x <= 'z'; bool ua = 'A' <= x && x <= 'Z'; bool dd = '0' <= x && x <= '9'; cout << la << " " << ua << " " << dd << endl; if(!(la || ua || dd)) return false; bool b1 = x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'; bool b2 = x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'; vowel = vowel || b1 || b2; consonant = consonant || !(b1 || b2) && !dd; } return vowel && consonant; } }; ``` ### 第二題 找出頻率最高的子字串即可,剩下的都替換成該子字串。 ```clike class Solution { public: int minimumOperationsToMakeKPeriodic(string word, int k) { const int n = word.size(); // substring count map<string, int> mm; for(int i = 0; i < n; i += k) { string s = word.substr(i, k); mm[s]++; } int ret = 0; vector<int> dd; for(auto it = mm.begin(); it != mm.end(); it++) { dd.push_back(it->second); } sort(dd.begin(), dd.end()); for(int i = 0; i < dd.size() - 1; i++) ret += dd[i]; return ret; } }; ``` ### 第三題 從討論區看解題思路,計算出字串 `s` 中每個字元的頻率後,求出所有頻率的最小公因數,答案即所有頻率除以該最小公因數。 我自己的想法是答案被最小頻率的字元限制,先找最小頻率的字元,再檢查是否能整除每個字元的頻率。 ```clike class Solution { public: using uit = unordered_map<char, int>::iterator; int minAnagramLength(string s) { unordered_map<char, int> mm; for(char x: s) mm[x]++; int mmin = INT_MAX; for(auto it = mm.begin(); it != mm.end(); it++) mmin = min(mmin, it->second); for(int i = mmin; i >= 1; i--) { bool c1 = solve(mm.begin(), mm, i); if(c1) { int ret = 0; for(auto it = mm.begin(); it != mm.end(); it++) ret += it->second / i; return ret; } } return s.size(); } bool solve(uit it, unordered_map<char, int> &mm, int c) { if(it == mm.end()) return true; bool c1 = it->second % c == 0; if(!c1) return false; bool c2 = solve(next(it), mm, c); return c2; } }; ```