63找到字符串中所有字母异位词(438)

作者: Turbo时间限制: 1S章节: 哈希表

晚于: 2020-08-19 12:00:00后提交分数乘系数50%

截止日期: 2020-08-26 12:00:00

问题描述 :

给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。

字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。

 

说明:

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

 

示例 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" 的字母异位词。

 

 

输入说明 :

输入两个字符串s和p,只包含小写英文字母,长度都不超过 20100

输出说明 :

输出一系列整数,为子串的起始索引,按照由小到大的顺序输出,整数之间以空格分隔。

如果起始索引集合为空,则输出“none”,不包括引号。

输入范例 :

输出范例 :

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;

class Solution {
public:
    vector<int> findAnagrams(string s, string p) 
    {
        if(s.size()<p.size())
            return {};
        int left=0,right=0;
        vector<int> now(26,0),need(26,0);//总共就26个字母 
        vector<int> ans;
        for(int i=0;i<p.size();i++)
        {
            need[p[i]-'a']++;
            now[s[right++]-'a']++;

        }
        if(now==need)//利用两个数组是否相等来判断 
            ans.push_back(0);
        while(right<s.size())
        {
            now[s[right++]-'a']++;//继续往后寻找 
            now[s[left++]-'a']--;//滑动窗口,后面的右移,前面的左移 
            if(now==need)
                ans.push_back(left);
        }
        return ans;
    }
};

int main()
{
    string s,p;
    cin>>s>>p;
    vector<int> res=Solution().findAnagrams(s,p);
    if(res.size()==0)
        cout<<"none"; 
    for(int i=0;i<res.size();i++)
    {
        if(i==res.size()-1)
            cout<<res[i];
        else
            cout<<res[i]<<" ";
    }
}

 

posted on 2020-09-09 17:23  Hi!Superman  阅读(182)  评论(0)    收藏  举报

导航