分两组:
/*
* @lc app=leetcode.cn id=2839 lang=cpp
*
* [2839] 判断通过操作能否让字符串相等 I
*/
// @lc code=start
class Solution
{
public:
bool canBeEqual(string s1, string s2)
{
return ((s1[0] == s2[0] && s1[2] == s2[2]) || (s1[0] == s2[2] && s1[2] == s2[0])) &&
((s1[1] == s2[1] && s1[3] == s2[3]) || (s1[1] == s2[3] && s1[3] == s2[1]));
}
};
// @lc code=end
时间复杂度:O(1)。
空间复杂度:O(1)。
用两个哈希表 cnt1 和 cnt2 分别统计字符串 s1 和 s2 奇偶下标的字符的出现次数。
比较两个哈希表,若相等,说明通过操作可以让字符串 s1 和 s2 相等,返回 true;否则,返回 false。
/*
* @lc app=leetcode.cn id=2840 lang=cpp
*
* [2840] 判断通过操作能否让字符串相等 II
*/
// @lc code=start
// 哈希
class Solution
{
public:
bool checkStrings(string s1, string s2)
{
int cnt1[2][26], cnt2[2][26];
memset(cnt1, 0, sizeof(cnt1));
memset(cnt2, 0, sizeof(cnt2));
for (int i = 0; i < s1.length(); i++)
{
cnt1[i % 2][s1[i] - 'a']++;
cnt2[i % 2][s2[i] - 'a']++;
}
return memcmp(cnt1, cnt2, sizeof(cnt1)) == 0;
}
};
// @lc code=end
时间复杂度:O(n+∣Σ∣),其中 n 为字符串 s1 的长度。
空间复杂度:O(∣Σ∣),其中 ∣Σ∣ 为字符集合的大小,本题中字符均为小写字母,所以 ∣Σ∣ = 26。
滑动窗口。
看到「长度固定的子数组」就要想到滑动窗口。
用一个哈希表 mp 维护窗口内的元素出现次数,当窗口内的 mp.size()>=m 时,更新子数组最大和。
/*
* @lc app=leetcode.cn id=2841 lang=cpp
*
* [2841] 几乎唯一子数组的最大和
*/
// @lc code=start
// 滑动窗口
class Solution
{
public:
long long maxSum(vector<int> &nums, int m, int k)
{
// 特判
if (nums.empty() || m > k)
return 0LL;
long long max_sum = 0LL;
vector<int> window;
unordered_map<int, int> mp;
long long sum = 0LL;
for (int i = 0; i < nums.size(); i++)
{
window.push_back(nums[i]);
mp[nums[i]]++;
sum += nums[i];
while (window.size() > k)
{
auto it = window.begin();
mp[*it]--;
if (mp[*it] == 0)
mp.erase(*it);
sum -= *it;
window.erase(it);
}
if (mp.size() >= m)
max_sum = max(max_sum, sum);
}
return max_sum;
}
};
// @lc code=end
时间复杂度:O(n),其中 n 为数组 nums 的长度。
空间复杂度:O(k)。哈希表的大小不会超过窗口长度,即 k。
哈希 + 组合数学。
提示:
统计每个字符出现次数的个数,然后从大到小遍历次数 c 及其个数 num。
所有方案数相乘即为答案。
如果 k 太大(循环中没有出现 num≥k),那么不存在合法子序列,返回 0。
/*
* @lc app=leetcode.cn id=2842 lang=cpp
*
* [2842] 统计一个字符串的 k 子序列美丽值最大的数目
*/
// @lc code=start
class Solution
{
private:
const int MOD = 1e9 + 7;
public:
int countKSubsequencesWithMaxBeauty(string s, int k)
{
vector<int> cnt(26, 0);
for (char &c : s)
cnt[c - 'a']++;
// STL map 会自动按键从小到大排序
map<int, int> cc;
for (int &c : cnt)
if (c)
cc[-c]++;
long long ans = 1;
for (auto &[c, num] : cc)
{
if (num >= k)
return ans * pow(-c, k) % MOD * comb(num, k) % MOD;
ans = ans * pow(-c, num) % MOD;
k -= num;
}
return 0;
}
// 辅函数 - 快速幂
long long pow(long long x, int n)
{
long long res = 1;
for (; n; n /= 2)
{
if (n % 2)
res = res * x % MOD;
x = x * x % MOD;
}
return res;
}
// 辅函数 - 求组合数 C(n,k)
long long comb(long long n, int k)
{
long long res = n;
for (int i = 2; i <= k; i++)
{
n--;
// n, n-1, n-2,... 中的前 i 个数至少有一个因子 i
res = res * n / i;
}
return res % MOD;
}
};
// @lc code=end
时间复杂度:O(n),其中 n 为字符串 s 的长度。
空间复杂度:O(∣Σ∣)。其中 ∣Σ∣ 为字符集合的大小,本题中字符均为小写字母,所以 ∣Σ∣=26。