ARTS Week 41
Algorithm 本周的算法题为 438. 找到字符串中所有字母异位词 给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词的子串,返回这些子串的起始索引。不考虑答案输出的顺序。 示例 1: 输入: s = "cbaebabacd", p = "abc" 输出: [0,6] 解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。 起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。 实现代码如下: const findAnagrams = function (s, p) { if (p.length > s.length) { return []; } let pCount = new Array(26).fill(0); let sCount = new Array(26).fill(0); let result = []; for (let char of p) { pCount[char.charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } for (let i = 0; i < p.length; i++) { sCount[s.charCodeAt(i) - 'a'.charCodeAt(0)] += 1; } if (isEqual(pCount, sCount)) { result.push(0); } for (let i = p.length; i < s.length; i++) { sCount[s.charCodeAt(i - p.length) - 'a'.charCodeAt(0)] -= 1; sCount[s.charCodeAt(i) - 'a'.charCodeAt(0)] += 1; if (isEqual(pCount, sCount)) { result.push(i - p.length + 1); } } function isEqual(count1, count2) { for (let i = 0; i < 26; i++) { if (count1[i] !== count2[i]) { return false; } } return true; } return result; }; 解题思路: 创建pCount和sCount字母表,通过一个字母的Unicode编码减去字母a的Unicode编码,得到其在字母表中的位置,并且将其计数,通过滑动窗口,左减右加,最后通过对比相同位置计数是否相等,来确定是否是字母异位词。 Review Eye colour change is riskiest cosmetic surgery - Breaking News English Lesson ...