LeetCode第49场双周赛题解
LeetCode第49场双周赛题解
判断国际象棋棋盘中一个格子的颜色
如果是a,c,e,g列,行数是偶数即为白格子,如果是b,d,f,h列,行数为奇数即为白格子
class Solution {
public:
bool squareIsWhite(string coordinates) {
char ch1 = coordinates[0], ch2 = coordinates[1];
if (ch1 == 'a' || ch1 == 'c' || ch1 == 'e' || ch1 == 'g') {
int p = ch2 - '0';
if (p & 1) return false;
return true;
}
int p = ch2 - '0';
if (p & 1) return true;
return false;
}
};
句子相似性 III
字符串模拟题。先分割字符串,把每一个字符串中的单词都单独存入 vector
中。把较长的字符串存入存入a中,较短的字符串存入b中。然后设置双指针 int i = 0, j = b.size() - 1;
分别指向b的首部和尾部,和a的字符串的头部和尾部开始进行比较,如果相同就 i++, j--
最后如果 i > j
说明两个句子相似。
class Solution {
public:
bool areSentencesSimilar(string sentence1, string sentence2) {
if (sentence1.size() < sentence2.size()) swap(sentence1,sentence2);
stringstream s1(sentence1), s2(sentence2);
vector a, b;
string str1, str2;
//分割所有的单词和字符
while(s1 >> str1) a.push_back(str1);
while(s2 >> str2) b.push_back(str2);
int i = 0, j = b.size() - 1;
for (int k = 0; k < a.size() && i < b.size(); k++) {
if (a[k] == b[i]) i++;
else break;
}
for (int k = a.size() - 1; k >= 0 && j >= 0; k--) {
if (a[k] == b[j]) j--;
else break;
}
return i > j;
}
};
5708. 统计一个数组中好对子的数目
由nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
可得
nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])
,用一个 unordered_map
统计每一个数字的 nums[i] - rev(nums[i])
出现频率即可。
class Solution {
public:
int rev(int x) {
int sum = 0;
while(x) {
sum = sum * 10 + x % 10;
x /= 10;
}
return sum;
}
int countNicePairs(vector& nums) {
const int MOD = 1e9 + 7;
unordered_map count;
int ans = 0;
for (int i = 0; i < nums.size(); i++) {
int tmp = nums[i] - rev(nums[i]);
ans = (ans + count[tmp]) % MOD;
count[tmp]++;
}
return ans;
}
};