C++ | Leetcode C++题解之第438题找到字符串中所有字母异位词

题目:

题解:

cpp 复制代码
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        int sLen = s.size(), pLen = p.size();

        if (sLen < pLen) {
            return vector<int>();
        }

        vector<int> ans;
        vector<int> count(26);
        for (int i = 0; i < pLen; ++i) {
            ++count[s[i] - 'a'];
            --count[p[i] - 'a'];
        }

        int differ = 0;
        for (int j = 0; j < 26; ++j) {
            if (count[j] != 0) {
                ++differ;
            }
        }

        if (differ == 0) {
            ans.emplace_back(0);
        }

        for (int i = 0; i < sLen - pLen; ++i) {
            if (count[s[i] - 'a'] == 1) {  // 窗口中字母 s[i] 的数量与字符串 p 中的数量从不同变得相同
                --differ;
            } else if (count[s[i] - 'a'] == 0) {  // 窗口中字母 s[i] 的数量与字符串 p 中的数量从相同变得不同
                ++differ;
            }
            --count[s[i] - 'a'];

            if (count[s[i + pLen] - 'a'] == -1) {  // 窗口中字母 s[i+pLen] 的数量与字符串 p 中的数量从不同变得相同
                --differ;
            } else if (count[s[i + pLen] - 'a'] == 0) {  // 窗口中字母 s[i+pLen] 的数量与字符串 p 中的数量从相同变得不同
                ++differ;
            }
            ++count[s[i + pLen] - 'a'];
            
            if (differ == 0) {
                ans.emplace_back(i + 1);
            }
        }

        return ans;
    }
};
相关推荐
辰烨chenye1 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
Keven_115 小时前
算法札记:ACM适用的很骚的C++语法(持续更新)
开发语言·c++
mengzhi啊5 小时前
QPluginLoader 动态 DLL 插件版,支持插件之间通信,广播。请求和应答
c++·qt
老赵的博客8 小时前
c++ QT之动态库加载问题
c++·qt
(Charon)9 小时前
【C++】定时器进阶:使用最小堆管理定时任务
c++·算法
hansang_IR9 小时前
【题解】 [省选联考 2021 A/B 卷] 卡牌游戏
c++·算法
lzx_0029 小时前
C++11(一)
开发语言·c++·算法
带多刺的玫瑰11 小时前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
小七在进步11 小时前
C++入门(2)
java·jvm·c++