题目:
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:
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:
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".
翻译:
给定一个字符串 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" 的一个字谜。
思路:
利用滑动窗口,首先将p中的字符和s中前p个字符分别映射为m1,m2,并进行比较,若m1==m2,那么结果result中加入0,表示从下标 0 开始的 s 中的p 个字符满足p的字谜,然后,s中的字符串从 p.size() 处开始,m1每加入一个新的字符,都删除掉一个旧的字符,然后继续比较m1和m2,直达扫描完s的整个串。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> result;
vector<int> m1(256, 0), m2(256, 0);
//map<char, int> m1), m2;
if (s.empty())
return {};
for (int i = 0; i < p.size(); i++) {
m1[s[i]]++;
m2[p[i]]++;
}
if (m1 == m2)
result.push_back(0);
for (int i = p.size(); i < s.size(); i++) {
m1[s[i]]++;
m1[s[i - p.size()]]--;
if (m1 == m2)
result.push_back(i - p.size() + 1);
}
return result;
}
};
int main()
{
Solution s;
string str = "abab";
string p = "ab";
vector<int> result;
result = s.findAnagrams(str, p);
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
return 0;
}