Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

438. Find All Anagrams in a String (window slide) #164

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public List findAnagrams(String s, String p) { List list = new ArrayList(); if(s == null || s.length() == 0 || p == null || p.length() ==0) return list; //存储p中的每个字符的hash值 int[] hash = new int[256]; for(char c : p.toCharArray()) { hash[c]++; } //设置两个指针right left,一个window-》count
int left = 0, right = 0, count = p.length(); while(right < s.length()) { //s从左到右扫描每个字符,如果存在,则window减去1 if(hash[s.charAt(right++)]-- >= 1) count--; //如果window是0,则证明符合,添加left坐标 if(count == 0) list.add(left); //要先判断right-left的长度,如果不符合马上跳出if,不会影响left和hash值 //该语句作用是恢复原始hash值和window长度
if(right - left == p.length() && hash[s.charAt(left++)]++ >= 0) count++; } return list; } }