アイデア:
(1) スライディング ウィンドウ
ここでのスライディング ウィンドウの中心となるアイデアは、まず長い文字列の中の短い文字列である最初の部分文字列をインターセプトし、次に右ポインタを右の ++ に移動し、左ポインタを移動することです。右側 – はそれぞれ、部分文字列を見つけることができるように、新しい数値を結合し、古い数値を減らすことを表します。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n = s1.length(), m = s2.length();
if (n > m) {
return false;
}
vector<int> cnt1(26), cnt2(26);
for (int i = 0; i < n; ++i) {
++cnt1[s1[i] - 'a'];
++cnt2[s2[i] - 'a'];
}
if (cnt1 == cnt2) {
return true;
}
for (int i = n; i < m; ++i) {
++cnt2[s2[i] - 'a'];
--cnt2[s2[i - n] - 'a'];
if (cnt1 == cnt2) {
return true;
}
}
return false;
}
};
アイデア:
上記のアイデアと似ていますが、一致するものが見つかったら、直接返さずにベクトルを使用して保存します。
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int n = p.length(), m = s.length();
vector<int>res;
if (n > m) {
return res;
}
vector<int> cnt1(26), cnt2(26);
for (int i = 0; i < n; ++i) {
++cnt1[p[i] - 'a'];
++cnt2[s[i] - 'a'];
}
if (cnt1 == cnt2) {
res.push_back(0);
}
for (int i = n; i < m; ++i) {
++cnt2[s[i] - 'a'];
--cnt2[s[i - n] - 'a'];
if (cnt1 == cnt2) {
res.push_back(i-n+1);
}
}
return res;
}
};