中国制造网服务种类,衡阳seo排名,中国糕点网页设计网站,中国政务服务网题目链接#xff1a;LCR 015. 找到字符串中所有字母异位词 - 力扣#xff08;LeetCode#xff09;
题目#xff1a;
输入字符串 s1 和 s2#xff0c;如何找出字符串 s2 的所有变位词在字符串 s1 中的起始下标#xff1f;假设两个字符串中只包含英文小写字母。例如…题目链接LCR 015. 找到字符串中所有字母异位词 - 力扣LeetCode
题目
输入字符串 s1 和 s2如何找出字符串 s2 的所有变位词在字符串 s1 中的起始下标假设两个字符串中只包含英文小写字母。例如字符串 s1 为 cbadabacg字符串 s2 为 abc字符串 s2 的两个变位词 cba 和 bac 是字符串 s1 中的子字符串输出它们在字符串 s1 中的起始下标 0 和 5。
分析
这个题目是面试题 14 字符串中的变位词 的变种。 《剑指 Offer》专项突破版 - 面试题 14 : 字符串中的变位词C 实现-CSDN博客 代码实现
class Solution {
public:bool areAllZero(const vectorint counts){for (int count : counts){if (count ! 0)return false;}return true;}
vectorint findAnagrams(string s, string p) {vectorint indices;int m s.size(), n p.size();if (m n)return indices;
vectorint counts(26, 0);for (int i 0; i n; i){counts[p[i] - a];--counts[s[i] - a];}
if (areAllZero(counts))indices.push_back(0);
for (int i n; i m; i){counts[s[i - n] - a];--counts[s[i] - a];if (areAllZero(counts))indices.push_back(i - n 1);}return indices;}
};