行业资讯

9 找到字符串中所有字母异位词

发布时间:2026/7/23 11:54:52
9 找到字符串中所有字母异位词 给定两个字符串s和p找到s中所有p的异位词的子串返回这些子串的起始索引。不考虑答案输出的顺序。示例 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 的异位词。提示:1 s.length, p.length 3 * 104s和p仅包含小写字母思路11、创建返回参数vectorint ans。检查参数的合法性s或者p为空、p的长度大于s时返回空vector。2、给p排序,分别求出s的长度s_len,p的长度p_len。3、创建两个指针left0,rightp_len-1。4、copy出left和right指向的字符串然后对其进行排序。5、判断排序两个字符串是否相等相等则将left的下标加入ans不相等则跳过。6、left和right都向前走一格直到right走到数组的最后一个位置。class Solution { public: vectorint findAnagrams(string s, string p) { vectorint ans; if(s.empty()||p.empty()||p.size()s.size()) return ans; if (s p) { ans.push_back(0); return ans; } sort(p.begin(),p.end()); int s_lens.size(); int p_lenp.size(); int left0,rightp_len-1; while(rights_len){ string _temps.substr(left,p_len); sort(_temp.begin(),_temp.end()); if(_tempp) ans.push_back(left); left; right; } return ans; } };结论该思路正确但是时间复杂度高无法通过全部用例思路21、不要用sort函数排序后再比较两个字符串是否相等。2、用一个vectorint word(26)类型的数组代表26个字母0代表a1代表b等以此类推。每出现该字母时该字母的下标1。比如出现一个a那么word[0]1出现一个b那么word[1]1以此类推。3、直接用vectorintvectorint的方法判断两个数组是否相等。步骤1、创建返回参数vectorint ans。检查参数的合法性s或者p为空、p的长度大于s时返回空vector和p完全相等时直接把0丢到ans中直接返回。2、创建一个vectorintword_s然后记录字符串p的字符个数。3、计算s和p的长度s_len、p_len。4、创建两个指针left和rightleft指向0right指向p_len-1开始循环。5、创建两个vectorint 数组word_s、word_p用于计算string的字符个数。6、先循环计算s字符串和p字符创left到righr上的字符串个数。7、while循环先判断两个word_s、word_p是否相等相等把left加入ans数组中不相等直接跳过。8、在word_s删掉left指向的字符leftright,把s[left]字符串加入word_s数组中。9、继续判断两个word_s、word_p是否相等直到循环结束。class Solution { public: vectorint findAnagrams(string s, string p) { vectorintans; int n_ss.size(); int n_pp.size(); if(n_s0||n_p0||n_pn_s) return ans; vectorint vec_s(26,0); vectorint vec_p(26,0); for(int i0;in_p;i){ vec_p[p[i]-a]; } int left0; int rightn_p-1; for(int i0;iright;i){ vec_s[s[i]-a]; } for(int iright;in_s;i){ vec_s[s[i]-a]; if(vec_pvec_s) ans.push_back(left); vec_s[s[left]-a]--; left; } return ans; } };推荐一个零声教育学习教程个人觉得老师讲得不错分享给大家[LinuxNginxZeroMQMySQLRedisfastdfsMongoDBZK流媒体CDNP2PK8SDockerTCP/IP协程DPDK等技术内容点击立即学习:链接