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;
    }
};
相关推荐
tyb33333312 分钟前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录42 分钟前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder12342 分钟前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode
宵时待雨43 分钟前
C++笔记归纳2:类和对象
c++·笔记
十五年专注C++开发1 小时前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
阿闽ooo1 小时前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
Sunsets_Red1 小时前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛
汉克老师1 小时前
GESP2023年12月认证C++二级( 第三部分编程题(2) 小杨的H字矩阵)
c++·算法·矩阵·循环结构·gesp二级·gesp2级
Charlie_lll1 小时前
力扣解题-438. 找到字符串中所有字母异位词
后端·算法·leetcode
奶茶树1 小时前
【数据结构】红黑树
数据结构·c++·算法