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;
    }
};
相关推荐
泽020216 分钟前
C++类和对象之相关特性
java·开发语言·c++
feiyangqingyun44 分钟前
Qt/C++开发监控GB28181系统/录像文件查询/录像回放/倍速播放/录像文件下载
c++·qt·gb28181·录像回放·录像文件下载
2301_807611491 小时前
310. 最小高度树
c++·算法·leetcode·深度优先·回溯
四谷夕雨2 小时前
C++八股——智能指针
c++
Once_day3 小时前
C++之fmt库介绍和使用(1)
开发语言·c++·fmt
是店小二呀3 小时前
【优选算法 | 字符串】字符串模拟题精选:思维+实现解析
android·c++·算法
不爱学英文的码字机器3 小时前
[操作系统] 策略模式进行日志模块设计
c++·策略模式
凤年徐3 小时前
【C/C++】自定义类型:结构体
c语言·开发语言·c++·经验分享·笔记·算法
DARLING Zero two♡3 小时前
C++效率掌握之STL库:map && set底层剖析及迭代器万字详解
c++·stl·set·map
绯樱殇雪3 小时前
编程题 02-线性结构3 Reversing Linked List【PAT】
c++·pat考试