classSolution { public: vector<int> decrypt(vector<int>& code, int k){ constint n = code.size(); vector<int> ans(n, 0); if (k == 0) { return ans; } elseif (k > 0) { for (int i = 0; i < n; ++i) { for (int j = 1; j <= k; ++j) { ans[i] += code[(i + j) % n]; } } return ans; } else { k = -k; for (int i = 0; i < n; ++i) { for (int j = 1; j <= k; ++j) { ans[i] += code[(i - j + n) % n]; } } return ans; } } };
时间复杂度: O(N),
空间复杂度: O(N).
5551. Minimum Deletions to Make String Balanced
枚举每个分割点,删除分割点前所有的b,和分割点后所有的a。找到最小删除数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intminimumDeletions(string s){ constint n = s.size(); int ans = n; constint totalA = count_if(s.begin(), s.end(), [](char c) -> bool { return c == 'a'; }); int a = 0, b = 0; for (int i = 0; i < n; ++i) { ans = min(ans, b + totalA - a); if (s[i] == 'a') ++a; else ++b; } ans = min(ans, b + totalA - a); return ans; } };