Every day a Leetcode
解法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。