Find All Anagrams in a String java using sliding window solution


  • 0
    A
    public List<Integer> findAnagrams(String s, String p) {
            
            List<Integer> result = new ArrayList<Integer>();
            int n = s.length();
            int m = p.length();
            
            if(n < m ) return result;
            
            int[] pArray = new int[256];
            int[] wArray = new int[256];
            
            
            // put chars in arrays till length of pattern
            for(int i= 0; i < m; i++) {
            	wArray[s.charAt(i)]++;
            	pArray[p.charAt(i)]++;
            }
            
            for(int j=m; j < n; j++) {
            	
            	if(compare(wArray, pArray)) {
            		result.add(j-m);
            	}
            	wArray[s.charAt(j)]++;
            	wArray[s.charAt(j-m)]--;
            	
            }
            
            if(compare(wArray, pArray)) {
        		result.add(n-m);
        	}
            
            return result;
        }
    
    	private boolean compare(int[] arr1, int[] arr2) {
    	
    		for(int i =0; i < 256; i++) {
    			if(arr1[i] != arr2[i]) return false;
    		}
    		
    		return true;
    	}
    

Log in to reply
 

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