Java Solution - not smart but easy to understand


  • 0
    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
        
        List<Integer> list = new ArrayList<Integer>();
        
        int sl = s.length();
        int pl = p.length();
        
        if(sl==0||pl==0||sl<pl) return list;
        
        int count = 0;
        int[] ar = new int[26];
    
        for (char c: p.toCharArray()){
            ar[c-'a']++;
        }
        
        for (int i=0;i<sl;i++) {
            
           if(ar[s.charAt(i)-'a']>0) {
                ar[s.charAt(i)-'a']--;
                count++;
            } else {
                int k=i;
                while (count>0){
                    ar[s.charAt(k-count)-'a']++;
                    count--; 
                    i--;
                }
            }
            
            if(count==pl){
                list.add(i-pl+1);
                count--;
                ar[s.charAt(i-pl+1)-'a']++;
            } 
        }
        return list;    
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.