A.
按题意一个个模拟即可
class Solution {
public:
bool strongPasswordCheckerII(string p) {
string sp = "!@#$%^&*()-+";
if (p.size() < 8) return false;
vector<int> vis(4, 0);
for (auto u : p) {
if (u >= 'a' && u <= 'z') vis[0] = 1;
if (u >= 'A' && u <= 'Z') vis[1] = 1;
if (u >= '0' && u <= '9') vis[2] = 1;
for (auto c : sp)
if (c == u) vis[3] = 1;
}
if (vis[0] + vis[1] + vis[2] + vis[3] < 4) return false;
for (int i = 1; i < p.size(); ++i)
if (p[i] == p[i - 1]) return false;
return true;
}
};
B.
对药水 p o t i o n s potions potions 进行排序,枚举咒语 s p e l l s spells spells ,二分使得 p o t i o n s [ i ] × s p e l l s [ j ] ≥ s u c c e s s potions[i]\times spells[j]\geq success potions[i]×spells[j]≥success 的最小 j j j ,从 j j j 到 n − 1 n-1 n−1 一定都是合法的。
class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(), potions.end());
int n = spells.size();
vector<int> ans(n, 0);
for (int i = 0; i < spells.size(); ++i) {
long long v = spells[i];
long long minv = success / v;
if (success % v != 0) minv += 1;
int m = potions.size();
auto it = lower_bound(potions.begin(), potions.end(), minv);
if (it != potions.end()) {
int p = it - potions.begin();
ans[i] = m - p;
}
}
return ans;
}
};
C.
二维数组建立映射关系,
枚举
s
u
b
sub
sub 中的串
s
u
b
s
t
r
substr
substr 是否可以替换成
s
s
s 即可。
class Solution {
public:
bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) {
int n = s.size(), m = sub.size();
vector<vector<int>> g(128, vector<int>(128, 0));
for (auto& u : mappings) g[u[0]][u[1]] = 1;
for (int i = 0; i + m - 1 < n; ++i) {
string temp = s.substr(i, m);
bool ok = true;
for (int j = 0; j < m; ++j)
if (temp[j] != sub[j]) {
if (g[sub[j]][temp[j]] == 0) {
ok = false;
break;
}
}
if (ok) return true;
}
return false;
}
};
D.
枚举右端点 r r r ,双指针来移动左端点 l l l 。因为都是正数,所以当短区间不合法时,长区间一定更不合法。一共 n × ( n + 1 ) 2 \frac{n\times (n+1)}{2} 2n×(n+1) 个区间,减去所有不合法的即所有合法的区间。
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
n = len(nums)
ans = n * (n + 1) // 2
s, c, l, r = 0, 0, 0, 0
while r < n:
c += 1
s += nums[r]
while l <= r and s * c >= k:
ans -= n - r
c -= 1
s -= nums[l]
l += 1
r += 1
return ans