给定两个字符串 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仅包含小写字母
核心思想:
1.建立两个数组,26的长度,索引分别对应26个字母,值对应的是每个字母出现的个数
2.一个数组存放是模板子串,另一个是滑动的窗口,每移动一位就和模板子串做比较是否相等
TypeScript
function findAnagrams(s: string, p: string): number[] {
const sL = s.length , pL = p.length
if(sL<pL) return []
const res:number[] = []
const pw = new Array(26).fill(0)
const window = new Array(26).fill(0)
// function charIndex(char:string):number{
// return char.charCodeAt(0)-97
// }
const charIndex = (char:string):number=> char.charCodeAt(0)-97
for(const pp of p){
pw[charIndex(pp)]++
}
function isSame(c1:number[],c2:number[]):boolean{
for(let i = 0 ;i<26;i++){
if(c1[i]!=c2[i]){
return false
}
}
return true
}
//初始化第一个窗口
for(let j = 0;j<pL;j++){
window[charIndex(s[j])]++
}
if(isSame(window,pw)) res.push(0)
//判断剩下的
for(let z = pL;z < sL ; z++){
window[charIndex(s[z-pL])]--
window[charIndex(s[z])]++
if(isSame(window,pw)) res.push(z-pL+1)
}
return res
};
今日收获
1.新建一个数组,长度是num,初始值填充为0
new Array(number).fill(0)
2.获得字符char对应的ASCⅡ码,'a'对应97,'b'对应98
char.charCodeAt(0) //0不要忽略,ts会报错
共勉