前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-438-Find All Anagrams in a String

leetcode-438-Find All Anagrams in a String

作者头像
chenjx85
发布2018-05-22 16:23:31
7510
发布2018-05-22 16:23:31
举报

题目描述:

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

代码语言:javascript
复制
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

代码语言:javascript
复制
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

要完成的函数:

vector<int> findAnagrams(string s, string p) 

说明:

1、给定一个字符串s和非空字符串p,将p中元素不断交换形成一个新的字符串,如果这个新的字符串在s中能找到匹配的,那么就输出匹配到的开始的位置,直到处理到字符串s结束。

2、这道题目难道要记住p经过交换可能形成的所有字符串吗,难道再类似于滑动窗口一般不断在s中比较?

其实不用记住所有字符串,记住p经过交换可能形成的所有字符串其实等价于记住p中所有字母出现的次数。

所以代码如下:

代码语言:javascript
复制
    vector<int> findAnagrams(string s, string p) 
    {
        vector<int>res;
        vector<int>p1(26,0);
        vector<int>s1(26,0);
        for(int i=0;i<p.size();i++)
        {
            p1[p[i]-'a']++;
        }
        for(int i=0;i<p.size();i++)
        {
            s1[s[i]-'a']++;
        }
        if(s.size()<p.size())
            return res;
        if(p1==s1)
            res.push_back(0);
        for(int i=1;i<=s.size()-p.size();i++)
        {
            s1[s[i-1]-'a']--;//当窗口滑动时,s1中要减去窗口前一位的字母1次
            s1[s[i-1+p.size()]-'a']++;//s1要加上窗口最后新的一维的字母1次
            if(s1==p1)
                res.push_back(i);
        }
        return res;
    }

上述代码实测35ms,beats 90.84% of cpp submissions。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档