第一题
创建一个哈希表,然后分别遍历key,message,遍历key,然后将字符写入哈希表,遇到重复则跳过,再遍历message将哈希表种的字符解密即可
class Solution {
public:
string decodeMessage(string key, string message) {
int ord[26] = {0}, cnt = 0;
for (char c : key) if (c >= 'a' && c <= 'z' && ord[c - 'a'] == 0) ord[c - 'a'] = ++cnt;
for (char &c : message) if (c >= 'a' && c <= 'z') c = ord[c - 'a'] - 1 + 'a';
return message;
}
};
第二题
该题可用方向矩阵依题意遍历二维矩阵然后进行赋值填充操作。
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> res(m, vector<int>(n, -1));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int x = 0, y = 0, d = 1;
for(int i = 0; i < n * m && head; i ++ ){
res[x][y] = head->val;
int a = x + dx[d], b = y + dy[d];
if(a < 0 || a >= m || b < 0 || b >= n || res[a][b] != -1){
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
head = head->next;
}
return res;
}
};
第三题
模拟然后递推
class Solution {
const int MOD = 1000000007;
public:
int peopleAwareOfSecret(int n, int delay, int forget) {
vector<long long> f(n + 1), g(n + 1);
f[1] = g[1] = 1;
for (int i = 2; i <= n; i++) {
int L = max(0, i - forget);
int R = max(0, i - delay);
f[i] = (g[R] - g[L] + MOD) % MOD;
g[i] = (g[i - 1] + f[i]) % MOD;
}
return (g[n] - g[max(0, n - forget)] + MOD) % MOD;
}
};