找到字符串中所有的字母异位词

题目链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
题目描述:

给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

异位词 指字母相同,但排列不同的字符串。

示例 1:
输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

示例 2:
输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。

提示:
1 <= s.length, p.length <= 3 * 104
s 和 p 仅包含小写字母

题解:

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> result;
        if(p.size() > s.size())
            return result;
        vector<int> winp(26, 0);
        vector<int> wins(26, 0);
        for(int i = 0; i < p.size(); i++)
        {
            winp[p[i] - 'a']++;
        }
        int slow = 0;
        for(int fast = 0; fast < s.size(); fast++)
        {
            wins[s[fast] - 'a']++;
            if(fast >= p.size())
            {
                wins[s[slow]-'a']--;
                slow++;
            }
            if(wins == winp)
                result.push_back(slow);

        }
        return result;

    }
};

posted @ 2021-10-03 18:48  张宵  阅读(43)  评论(0编辑  收藏  举报