本题用到了滑动窗口。共有两种解法,分别用map实现滑动窗口 和 用数组实现滑动窗口。
统计字符串p中每个字符出现的次数,用map或者数组存储,map存储是<Character, Integer>,数组存储是num[(int)(char - 'a')] = frequency,将字符串p存储完整形成pcount
然后对字符串s从位置0开始遍历,将第i个字符存入map或数组,如果i>=字符串p的长度,删除掉第i-plen个字符,维护一个scount,如果pcount等于scount,记录i-plen+1的位置。
几点语法:
1.map中如果val==1。java删除key操作:map.remover(key) python删除key操作: del map[key]。
2.python中转ASCII用ord(char) - ord('a'),java中转ASCII直接转int型(int)(char - 'a')。
3.python中Counter的使用。
JAVA
public class Solution { public List<Integer> findAnagrams(String s, String p) { Map<Character, Integer> pcount = new HashMap<>(); Map<Character, Integer> scount = new HashMap<>(); List<Integer> res = new LinkedList<>(); int plen = p.length(); int slen = s.length(); if(plen > slen) return res; for(char c: p.toCharArray()){ pcount.put(c, pcount.getOrDefault(c, 0)+1); } for(int i = 0; i < slen; i++){ scount.put(s.charAt(i), scount.getOrDefault(s.charAt(i), 0)+1); if(i >= plen){ char c = s.charAt(i-plen); if(scount.get(c)==1) scount.remove(c); //删除key else scount.put(c, scount.get(c)-1); } if(pcount.equals(scount)) res.add(i-plen+1); } return res; } }
public class Solution { public List<Integer> findAnagrams(String s, String p) { int[] pcount = new int[26]; int[] scount = new int[26]; List<Integer> res = new LinkedList<>(); int plen = p.length(); int slen = s.length(); if(plen > slen) return res; for(char c: p.toCharArray()){ pcount[(int)(c - 'a')]++; } for(int i = 0; i < slen; i++){ scount[(int)(s.charAt(i)-'a')]++; if(i >= plen){ scount[(int)(s.charAt(i-plen)-'a')]--; } if(Arrays.equals(pcount, scount)) res.add(i-plen+1); } return res; } }
Python3
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: res = [] pcount = collections.Counter(p) scount = collections.Counter() print(pcount) slen = len(s) plen = len(p) if slen < plen: return res for i in range(slen): scount[s[i]] += 1 if i >= plen: if scount[s[i-plen]] == 1: del scount[s[i-plen]] else: scount[s[i-plen]] -= 1 if pcount == scount: res.append(i-plen+1) return res
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: res = [] pcount = [0]*26 scount = [0]*26 slen = len(s) plen = len(p) if slen < plen: return res for c in p: pcount[ord(c) - ord('a')] += 1 for i in range(slen): scount[ord(s[i])-ord('a')] += 1 if i >= plen: scount[ord(s[i-plen])-ord('a')] -= 1 if pcount == scount: res.append(i-plen+1) return res